home *** CD-ROM | disk | FTP | other *** search
/ MacGames Sampler / PHT MacGames Bundle.iso / MacSource Folder / Samples from the CD / Editors / emacs / Emacs-1.14b1 / lisp / dired.el < prev    next >
Encoding:
Text File  |  1993-12-29  |  140.3 KB  |  3,677 lines  |  [TEXT/EMAC]

  1. ;; DIRED commands for Emacs.  $Revision: 6.0 $
  2. ;; Copyright (C) 1985, 1986, 1991 Free Software Foundation, Inc.
  3.  
  4. ;; This file is part of GNU Emacs.
  5.  
  6. ;; GNU Emacs is free software; you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation; either version 1, or (at your option)
  9. ;; any later version.
  10.  
  11. ;; GNU Emacs is distributed in the hope that it will be useful,
  12. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. ;; GNU General Public License for more details.
  15.  
  16. ;; You should have received a copy of the GNU General Public License
  17. ;; along with GNU Emacs; see the file COPYING.  If not, write to
  18. ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  19.  
  20. ;; Rewritten in 1990/1991 to add tree features, file marking and
  21. ;; sorting by Sebastian Kremer <sk@thp.uni-koeln.de>.
  22.  
  23. (provide 'dired)
  24.  
  25. (defconst dired-version (substring "$Revision: 6.0 $" 11 -2)
  26.   "The revision number of Tree Dired (as string).  The complete RCS id is:
  27.  
  28.   $Id: dired.el,v 6.0 1992/05/15 14:25:45 sk RelBeta $
  29.  
  30. Don't forget to mention this when reporting bugs to:
  31.  
  32.   Sebastian Kremer <sk@thp.uni-koeln.de>
  33.  
  34. Tree dired is available for anonymous ftp in USA in:
  35.  
  36.   ftp.cs.buffalo.edu:pub/Emacs/diredall.tar.Z
  37.  
  38. and in Europe at my own site in Germany:
  39.  
  40.   ftp.uni-koeln.de:/pub/gnu/emacs/diredall.tar.Z")
  41. ;; Should perhaps later give bug-gnu-emacs@prep.gnu.ai.mit.edu instead.
  42.  
  43. ;; compatibility package when using Emacs 18.55
  44. (defvar dired-emacs-19-p (equal (substring emacs-version 0 2) "19"))
  45. ;;;>>> install (is there a better way to test for Emacs 19?)
  46. (or dired-emacs-19-p
  47.     (require 'emacs-19))
  48.  
  49. ;;; Customizable variables
  50.  
  51. ;;; The funny comments are for autoload.el, to automagically update
  52. ;;; loaddefs.
  53.  
  54. ;;;###autoload
  55. (defvar dired-listing-switches "-al"
  56.   "*Switches passed to ls for dired. MUST contain the `l' option.
  57. Can contain even `F', `b', `i' and `s'.")
  58.  
  59. ; Don't use absolute paths as /bin should be in any PATH and people
  60. ; may prefer /usr/local/gnu/bin or whatever.  However, chown is
  61. ; usually not in PATH.
  62.  
  63. ;;;###autoload
  64. (defvar dired-chown-program
  65.   (if (memq system-type '(hpux dgux usg-unix-v)) "chown" "/etc/chown")
  66.   "*Name of chown command (usully `chown' or `/etc/chown').")
  67.  
  68. ;;;###autoload
  69. (defvar dired-ls-program "ls"
  70.   "*Absolute or relative name of the ls program used by dired.")
  71.  
  72. ;;;###autoload
  73. (defvar dired-ls-F-marks-symlinks t
  74.   "*Informs dired about how ls -lF marks symbolic links.
  75. Set this to t if `dired-ls-program' with -lF marks the symbolic link
  76. itself with a trailing @ (usually the case under Ultrix).
  77.  
  78. Example: if `ln -s foo bar; ls -F bar' gives `bar -> foo', set it to
  79. nil, if it gives `bar@ -> foo', set it to t.
  80.  
  81. Dired checks if there is really a @ appended.  Thus, if you have a
  82. marking ls program on one host and a non-marking on another host, and
  83. don't care about symbolic links which really end in a @, you can
  84. always set this variable to t.")
  85.  
  86. ;;;###autoload
  87. (defvar dired-trivial-filenames "^\\.\\.?$\\|^#"
  88.   "*Regexp of files to skip when moving point to the first file of a new directory listing.
  89. Nil means move to the subdir line, t means move to first file.")
  90.  
  91. ;;;###autoload
  92. (defvar dired-keep-marker-move t
  93.   ;; Use t as default so that moved files `take their markers with them'
  94.   "If t, moved marked files are marked if their originals were.
  95. If a character, those files (marked or not) are marked with that character.")
  96.  
  97. ;;;###autoload
  98. (defvar dired-keep-marker-copy ?C
  99.     "If t, copied files are marked if their source files were.
  100. If a character, those files are always marked with that character.")
  101.  
  102. ;;;###autoload
  103. (defvar dired-keep-marker-hardlink ?H
  104.     "If t, hard-linked files are marked if the linked-to files were.
  105. If a character, those files are always marked with that character.")
  106.  
  107. ;;;###autoload
  108. (defvar dired-keep-marker-symlink ?Y
  109.     "If t, symlinked marked files are marked if the linked-to files were.
  110. If a character, those files are always marked with that character.")
  111.  
  112. ;;;###autoload
  113. (defvar dired-dwim-target nil
  114.   "*If non-nil, dired tries to guess a default target directory:
  115. If there is a dired buffer displayed in the next window, use
  116. its current subdir, instead of the current subdir of this dired
  117. buffer.
  118.  
  119. The target is used in the prompt for file copy, move etc.")
  120.  
  121. ;;;###autoload
  122. (defvar dired-copy-preserve-time nil
  123.   "*If non-nil, Dired preserves the last-modified time in a file copy.
  124. \(This works on only some systems.)\\<dired-mode-map>
  125. Use `\\[dired-do-copy]' with a zero prefix argument to toggle its value.")
  126.  
  127. ;;; Hook variables
  128.  
  129. (defvar dired-load-hook nil
  130.   "Run after loading dired.
  131. You can customize key bindings or load extensions with this.")
  132.  
  133. (defvar dired-mode-hook nil
  134.   "Run at the very end of dired-mode.")
  135.  
  136. (defvar dired-before-readin-hook nil
  137.   "This hook is run before a dired buffer is newly read in (created or reverted).")
  138.  
  139. (defvar dired-after-readin-hook nil
  140.   "After each listing of a file or directory, this hook is run
  141. with the buffer narrowed to the listing.")
  142. ;; Note this can't simply be run inside function dired-ls as the hook
  143. ;; functions probably depend on the dired-subdir-alist to be OK.
  144.  
  145. ;;; Internal variables
  146.  
  147. (defvar dired-marker-char ?*        ; the answer is 42
  148.   ;; so that you can write things like
  149.   ;; (let ((dired-marker-char ?X))
  150.   ;;    ;; great code using X markers ...
  151.   ;;    )
  152.   ;; For example, commands operating on two sets of files, A and B.
  153.   ;; Or marking files with digits 0-9.  This could implicate
  154.   ;; concentric sets or an order for the marked files.
  155.   ;; The code depends on dynamic scoping on the marker char.
  156.   "In dired, character used to mark files for later commands.")
  157.  
  158. (defvar dired-del-marker ?D
  159.   "Character used to flag files for deletion.")
  160.  
  161. (defvar dired-shrink-to-fit
  162.   (if (fboundp 'baud-rate) (> (baud-rate) search-slow-speed) t)
  163.   "Whether dired shrinks the display buffer to fit the marked files.")
  164.  
  165. (defvar dired-flagging-regexp nil);; Last regexp used to flag files.
  166.  
  167. (defvar dired-directory nil
  168.   "The directory name or shell wildcard passed as argument to ls.
  169. Local to each dired buffer.")
  170.  
  171. (defvar dired-actual-switches nil
  172.   "The actual (buffer-local) value of `dired-listing-switches'.")
  173.  
  174. (defvar dired-re-inode-size "[0-9 \t]*"
  175.   "Regexp for optional initial inode and file size as produced by ls' -i and -s flags.")
  176.  
  177. ;; These regexps must be tested at beginning-of-line, but are also
  178. ;; used to search for next matches, so neither omitting "^" nor
  179. ;; replacing "^" by "\n" (to make it slightly faster) will work.
  180.  
  181. (defvar dired-re-mark "^[^ \n]")
  182. ;; "Regexp matching a marked line.
  183. ;; Important: the match ends just after the marker."
  184. (defvar dired-re-maybe-mark "^. ")
  185. ;; Note that dired-re-inode-size allows for an arbitray amount of
  186. ;; whitespace, making nested indentation in dired-nstd.el work.
  187. (defvar dired-re-dir (concat dired-re-maybe-mark dired-re-inode-size "d"))
  188. (defvar dired-re-sym (concat dired-re-maybe-mark dired-re-inode-size "l"))
  189. (defvar dired-re-exe;; match ls permission string of an executable file
  190.   (mapconcat (function
  191.           (lambda (x)
  192.         (concat dired-re-maybe-mark dired-re-inode-size x)))
  193.          '("-[-r][-w][xs][-r][-w].[-r][-w]."
  194.            "-[-r][-w].[-r][-w][xs][-r][-w]."
  195.            "-[-r][-w].[-r][-w].[-r][-w][xst]")
  196.          "\\|"))
  197. (defvar dired-re-dot "^.* \\.\\.?/?$")    ; with -F, might end in `/'
  198.  
  199. (defvar dired-subdir-alist nil
  200.   "Association list of subdirectories and their buffer positions:
  201.  
  202.   \((LASTDIR . LASTMARKER) ... (DEFAULT-DIRECTORY . FIRSTMARKER)).")
  203.  
  204. (defvar dired-subdir-regexp "^. \\([^ \n\r]+\\)\\(:\\)[\n\r]"
  205.   "Regexp matching a maybe hidden subdirectory line in ls -lR output.
  206. Subexpression 1 is the subdirectory proper, no trailing colon.
  207. The match starts at the beginning of the line and ends after the end
  208. of the line (\\n or \\r).
  209. Subexpression 2 must end right before the \\n or \\r.")
  210.  
  211.  
  212. ;;; Macros must be defined before they are used - for the byte compiler.
  213.  
  214. ;; Returns the count if any work was done, nil otherwise.
  215. (defmacro dired-mark-if (predicate msg)
  216.   (` (let (buffer-read-only count)
  217.        (save-excursion
  218.      (setq count 0)
  219.      (if (, msg) (message "Marking %ss..." (, msg)))
  220.      (goto-char (point-min))
  221.      (while (not (eobp))
  222.        (if (, predicate)
  223.            (progn
  224.          (delete-char 1)
  225.          (insert dired-marker-char)
  226.          (setq count (1+ count))))
  227.        (forward-line 1))
  228.      (if (, msg) (message "%s %s%s %s%s."
  229.               count
  230.               (, msg)
  231.               (dired-plural-s count)
  232.               (if (eq dired-marker-char ?\040) "un" "")
  233.               (if (eq dired-marker-char dired-del-marker)
  234.                   "flagged" "marked"))))
  235.        (and (> count 0) count))))
  236.  
  237. (defmacro dired-mark-map (body arg &optional show-progress)
  238. ;;  "Macro: Perform BODY with point somewhere on each marked line
  239. ;;and return a list of BODY's results.
  240. ;;If no marked file could be found, execute BODY on the current line.
  241. ;;  If ARG is an integer, use the next ARG (or previous -ARG, if ARG<0)
  242. ;;  files instead of the marked files.
  243. ;;  In that case point is dragged along.  This is so that commands on
  244. ;;  the next ARG (instead of the marked) files can be chained easily.
  245. ;;  If ARG is otherwise non-nil, use current file instead.
  246. ;;If optional third arg SHOW-PROGRESS evaluates to non-nil,
  247. ;;   redisplay the dired buffer after each file is processed.
  248. ;;No guarantee is made about the position on the marked line.
  249. ;;  BODY must ensure this itself if it depends on this.
  250. ;;Search starts at the beginning of the buffer, thus the car of the list
  251. ;;  corresponds to the line nearest to the buffer's bottom.  This
  252. ;;  is also true for (positive and negative) integer values of ARG.
  253. ;;BODY should not be too long as it is expanded four times."
  254. ;;
  255. ;;Warning: BODY must not add new lines before point - this may cause an
  256. ;;endless loop.
  257. ;;This warning should not apply any longer, sk  2-Sep-1991 14:10.
  258.   (` (prog1
  259.      (let (buffer-read-only case-fold-search found results)
  260.        (if (, arg)
  261.            (if (integerp (, arg))
  262.            (progn;; no save-excursion, want to move point.
  263.              (dired-repeat-over-lines
  264.               (, arg)
  265.               (function (lambda ()
  266.                   (if (, show-progress) (sit-for 0))
  267.                   (setq results (cons (, body) results)))))
  268.              (if (< (, arg) 0)
  269.              (nreverse results)
  270.                results))
  271.          ;; non-nil, non-integer ARG means use current file:
  272.          (list (, body)))
  273.          (let ((regexp (dired-marker-regexp)) next-position)
  274.            (save-excursion
  275.          (goto-char (point-min))
  276.          ;; remember position of next marked file before BODY
  277.          ;; can insert lines before the just found file,
  278.          ;; confusing us by finding the same marked file again
  279.          ;; and again and...
  280.          (setq next-position (and (re-search-forward regexp nil t)
  281.                       (point-marker))
  282.                found (not (null next-position)))
  283.          (while next-position
  284.            (goto-char next-position)
  285.            (if (, show-progress) (sit-for 0))
  286.            (setq results (cons (, body) results))
  287.            ;; move after last match
  288.            (goto-char next-position)
  289.            (forward-line 1)
  290.            (set-marker next-position nil)
  291.            (setq next-position (and (re-search-forward regexp nil t)
  292.                         (point-marker)))))
  293.            (if found
  294.            results
  295.          (list (, body))))))
  296.        ;; save-excursion loses, again
  297.        (dired-move-to-filename))))
  298.  
  299. (defun dired-mark-get-files (&optional localp arg)
  300.   "Return the marked files as list of strings.
  301. The list is in the same order as the buffer, that is, the car is the
  302.   first marked file.
  303. Values returned are normally absolute pathnames.
  304. Optional arg LOCALP as in `dired-get-filename'.
  305. Optional second argument ARG forces to use other files.  If ARG is an
  306.   integer, use the next ARG files.  If ARG is otherwise non-nil, use
  307.   current file.  Usually ARG comes from the current prefix arg."
  308.   (nreverse (save-excursion (dired-mark-map (dired-get-filename localp) arg))))
  309.  
  310.  
  311. ;; Function dired-ls is redefinable for VMS, ange-ftp, Prospero or
  312. ;; other special applications.
  313.  
  314. ;; dired-ls
  315. ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
  316. ;;   FULL-DIRECTORY-P is nil.
  317. ;;   The single line of output must display FILE's name as it was
  318. ;;   given, namely, an absolute path name.
  319. ;; - must insert exactly one line for each file if WILDCARD or
  320. ;;   FULL-DIRECTORY-P is t, plus one optional "total" line
  321. ;;   before the file lines, plus optional text after the file lines.
  322. ;;   Lines are delimited by "\n", so filenames containing "\n" are not
  323. ;;   allowed.
  324. ;;   File lines should display the basename, not a path name.
  325. ;; - must drag point after inserted text
  326. ;; - must be consistent with
  327. ;;   - functions dired-move-to-filename, (these two define what a file line is)
  328. ;;            dired-move-to-end-of-filename,
  329. ;;         dired-between-files, (shortcut for (not (dired-move-to-filename)))
  330. ;;            dired-insert-headerline
  331. ;;            dired-after-subdir-garbage (defines what a "total" line is)
  332. ;;   - variables dired-subdir-regexp
  333. (defun dired-ls (file switches &optional wildcard full-directory-p)
  334. ;  "Insert ls output of FILE, formatted according to SWITCHES.
  335. ;Optional third arg WILDCARD means treat FILE as shell wildcard.
  336. ;Optional fourth arg FULL-DIRECTORY-P means file is a directory and
  337. ;switches do not contain `d', so that a full listing is expected.
  338. ;
  339. ;Uses dired-ls-program (and shell-file-name if WILDCARD) to do the work."
  340.   (if wildcard
  341.       (let ((default-directory (file-name-directory file)))
  342.     (call-process shell-file-name nil t nil
  343.               "-c" (concat dired-ls-program " -d " switches " "
  344.                    (file-name-nondirectory file))))
  345.     (call-process dired-ls-program nil t nil switches file)))
  346.  
  347. ;; The dired command
  348.  
  349. (defun dired-read-dir-and-switches (str)
  350.   ;; For use in interactive.
  351.   (reverse (list
  352.         (if current-prefix-arg
  353.         (read-string "Dired listing switches: "
  354.                  dired-listing-switches))
  355.         (read-file-name (format "Dired %s(directory): " str)
  356.                 nil default-directory nil))))
  357.  
  358. ;;;###autoload (define-key ctl-x-map "d" 'dired)
  359. ;;;###autoload
  360. (defun dired (dirname &optional switches)
  361.   "\"Edit\" directory DIRNAME--delete, rename, print, etc. some files in it.
  362. With an optional prefix argument you can specify the ls SWITCHES that are used.
  363. Dired displays a list of files in DIRNAME (which may also have
  364.   shell wildcards appended to select certain files).
  365. You can move around in it with the usual commands.
  366. You can flag files for deletion with \\<dired-mode-map>\\[dired-flag-file-deleted] and then delete them by
  367.   typing \\[dired-do-deletions].
  368. Type \\[describe-mode] after entering dired for more info.
  369.  
  370. If DIRNAME is already in a dired buffer, that buffer is used without refresh."
  371.   ;; Cannot use (interactive "D") because of wildcards.
  372.   (interactive (dired-read-dir-and-switches ""))
  373.   (switch-to-buffer (dired-noselect dirname switches)))
  374.  
  375. ;;;###autoload (define-key ctl-x-4-map "d" 'dired-other-window)
  376. ;;;###autoload
  377. (defun dired-other-window (dirname &optional switches)
  378.   "\"Edit\" directory DIRNAME.  Like `dired' but selects in another window."
  379.   (interactive (dired-read-dir-and-switches "in other window "))
  380.   (switch-to-buffer-other-window (dired-noselect dirname switches)))
  381.  
  382. ;;;###autoload
  383. (defun dired-noselect (dirname &optional switches)
  384.   "Like `dired' but returns the dired buffer as value, does not select it."
  385.   (or dirname (setq dirname default-directory))
  386.   ;; This loses the distinction between "/foo/*/" and "/foo/*" that
  387.   ;; some shells make:
  388.   (setq dirname (expand-file-name (directory-file-name dirname)))
  389.   (if (file-directory-p dirname)
  390.       (setq dirname (file-name-as-directory dirname)))
  391.   (dired-internal-noselect dirname switches))
  392.  
  393. ;; Separate function from dired-noselect for the sake of dired-vms.el.
  394. (defun dired-internal-noselect (dirname &optional switches)
  395.   ;; If there is an existing dired buffer for DIRNAME, just leave
  396.   ;; buffer as it is (don't even call dired-revert).
  397.   ;; This saves time especially for deep trees or with ange-ftp.
  398.   ;; The user can type `g'easily, and it is more consistent with find-file.
  399.   ;; But if SWITCHES are given they are probably different from the
  400.   ;; buffer's old value, so call dired-sort-other, which does
  401.   ;; revert the buffer.
  402.   ;; A pity we can't possibly do "Directory has changed - refresh? "
  403.   ;; like find-file does...maybe in the GNU OS.
  404.   (let* ((buffer (dired-find-buffer-nocreate dirname))
  405.      ;; note that buffer already is in dired-mode, if found
  406.      (new-buffer-p (not buffer))
  407.      (old-buf (current-buffer)))
  408.     (or buffer
  409.     (let ((default-major-mode 'fundamental-mode))
  410.       ;; We don't want default-major-mode to run hooks and set auto-fill
  411.       ;; or whatever, now that dired-mode does not
  412.       ;; kill-all-local-variables any longer.
  413.       (setq buffer (create-file-buffer (directory-file-name dirname)))))
  414.     (set-buffer buffer)
  415.     (if (not new-buffer-p)        ; existing buffer ...
  416.     (if switches            ; ... but new switches
  417.         (dired-sort-other switches))    ; this calls dired-revert
  418.       ;; Else a new buffer
  419.       (setq default-directory (if (file-directory-p dirname)
  420.                   dirname
  421.                 (file-name-directory dirname)))
  422.       (or switches (setq switches dired-listing-switches))
  423.       (dired-mode dirname switches)
  424.       ;; default-directory and dired-actual-switches are set now
  425.       ;; (buffer-local), so we can call dired-readin:
  426.       (let ((failed t))
  427.     (unwind-protect
  428.         (progn (dired-readin dirname buffer)
  429.            (setq failed nil))
  430.       ;; dired-readin can fail if parent directories are inaccessible.
  431.       ;; Don't leave an empty buffer around in that case.
  432.       (if failed (kill-buffer buffer))))
  433.       ;; No need to narrow since the whole buffer contains just
  434.       ;; dired-readin's output, nothing else.  The hook can
  435.       ;; successfully use dired functions (e.g. dired-get-filename)
  436.       ;; as the subdir-alist has been built in dired-readin.
  437.       (run-hooks 'dired-after-readin-hook)
  438.       (goto-char (point-min))
  439.       (dired-initial-position dirname))
  440.     (set-buffer old-buf)
  441.     buffer))
  442.  
  443. ;; This differs from dired-buffers-for-dir in that it does not consider
  444. ;; subdirs of default-directory and searches for the first match only
  445. (defun dired-find-buffer-nocreate (dirname)
  446.   (let (found (blist (buffer-list)))
  447.     (while blist
  448.       (save-excursion
  449.         (set-buffer (car blist))
  450.     (if (and (eq major-mode 'dired-mode)
  451.          (equal dired-directory dirname))
  452.         (setq found (car blist)
  453.           blist nil)
  454.       (setq blist (cdr blist)))))
  455.     found))
  456.  
  457.  
  458. ;; Read in a new dired buffer
  459.  
  460. ;; dired-readin differs from dired-insert-subdir in that it accepts
  461. ;; wildcards, erases the buffer, and builds the subdir-alist anew
  462. ;; (including making it buffer-local and clearing it first).
  463. (defun dired-readin (dirname buffer)
  464.   ;; default-directory and dired-actual-switches must be buffer-local
  465.   ;; and initialized by now.
  466.   ;; Thus we can test (equal default-directory dirname) instead of
  467.   ;; (file-directory-p dirname) and save a filesystem transaction.
  468.   ;; Also, we can run this hook which may want to modify the switches
  469.   ;; based on default-directory, e.g. with ange-ftp to a SysV host
  470.   ;; where ls won't understand -Al switches.
  471.   (setq dirname (expand-file-name dirname))
  472.   (run-hooks 'dired-before-readin-hook)
  473.   (save-excursion
  474.     (message "Reading directory %s..." dirname)
  475.     (set-buffer buffer)
  476.     (let (buffer-read-only)
  477.       (widen)
  478.       (erase-buffer)
  479.       (dired-readin-insert dirname)
  480.       (indent-rigidly (point-min) (point-max) 2)
  481.       ;; We need this to make the root dir have a header line as all
  482.       ;; other subdirs have:
  483.       (goto-char (point-min))
  484.       (dired-insert-headerline default-directory)
  485.       ;; can't run dired-after-readin-hook here, it may depend on the subdir
  486.       ;; alist to be OK.
  487.       )
  488.     (message "Reading directory %s...done" dirname)
  489.     (set-buffer-modified-p nil)
  490.     ;; Must first make alist buffer local and set it to nil because
  491.     ;; dired-build-subdir-alist will call dired-clear-alist first
  492.     (set (make-local-variable 'dired-subdir-alist) nil)
  493.     (let (case-fold-search)
  494.       (if (string-match "R" dired-actual-switches)
  495.       (dired-build-subdir-alist)
  496.     ;; no need to parse the buffer if listing is not recursive
  497.     (dired-simple-subdir-alist)))))
  498.  
  499. ;; Subroutines of dired-readin
  500.  
  501. (defun dired-readin-insert (dirname)
  502.   ;; Just insert listing for DIRNAME, assuming a clean buffer.
  503.   (if (equal default-directory dirname);; i.e., (file-directory-p dirname)
  504.       (dired-ls (if (or (let (case-fold-search)
  505.               (string-match "R" dired-actual-switches))
  506.             (eq system-type 'vax-vms))
  507.             dirname
  508.           ;; On SysV derived system, symbolic links to
  509.           ;; directories are not resolved, while on BSD
  510.           ;; derived it suffices to let DIRNAME end in slash.
  511.           ;; We always let it end in "/." since it does no
  512.           ;; harm on BSD and makes Dired work on such links on
  513.           ;; SysV.
  514.           ;; Cannot do this with -R since "dir/./subdir"
  515.           ;; headerlines would result, utterly confusing dired.
  516.           (concat dirname "."))
  517.         dired-actual-switches nil t)
  518.     (if (not (file-readable-p
  519.           (directory-file-name (file-name-directory dirname))))
  520.     (error "Directory %s inaccessible or nonexistent" dirname)
  521.       ;; else assume it contains wildcards:
  522.       (dired-ls dirname dired-actual-switches t)
  523.       (save-excursion;; insert wildcard instead of total line:
  524.     (goto-char (point-min))
  525.     (insert "wildcard " (file-name-nondirectory dirname) "\n")))))
  526.  
  527. (defun dired-insert-headerline (dir);; also used by dired-insert-subdir
  528.   ;; Insert DIR's headerline with no trailing slash, exactly like ls
  529.   ;; would, and put cursor where dired-build-subdir-alist puts subdir
  530.   ;; boundaries.
  531.   (save-excursion (insert "  " (directory-file-name dir) ":\n")))
  532.  
  533.  
  534. ;; Reverting a dired buffer
  535.  
  536. (defun dired-revert (&optional arg noconfirm)
  537.   ;; Reread the dired buffer.  Must also be called after
  538.   ;; dired-actual-switches have changed.
  539.   ;; Should not fail even on completely garbaged buffers.
  540.   ;; Preserves old cursor, marks/flags, hidden-p.
  541.   (widen)                ; just in case user narrowed
  542.   (let ((opoint (point))
  543.     (ofile (dired-get-filename nil t))
  544.     (mark-alist nil)        ; save marked files
  545.     (hidden-subdirs (dired-remember-hidden))
  546.     (old-subdir-alist (cdr (reverse dired-subdir-alist))) ; except pwd
  547.     case-fold-search        ; we check for upper case ls flags
  548.     buffer-read-only)
  549.     (goto-char (point-min))
  550.     (setq mark-alist;; only after dired-remember-hidden since this unhides:
  551.       (dired-remember-marks (point-min) (point-max)))
  552.     ;; treat top level dir extra (it may contain wildcards)
  553.     (dired-readin dired-directory (current-buffer))
  554.     (let ((dired-after-readin-hook nil))
  555.       ;; don't run that hook for each subdir...
  556.       (dired-insert-old-subdirs old-subdir-alist))
  557.     (dired-mark-remembered mark-alist)    ; mark files that were marked
  558.     ;; ... run the hook for the whole buffer, and only after markers
  559.     ;; have been reinserted (else omitting in dired-x would omit marked files)
  560.     (run-hooks 'dired-after-readin-hook)    ; no need to narrow
  561.     (or (and ofile (dired-goto-file ofile)) ; move cursor to where it
  562.     (goto-char opoint))        ; was before
  563.     (dired-move-to-filename)
  564.     (save-excursion            ; hide subdirs that were hidden
  565.       (mapcar (function (lambda (dir)
  566.               (if (dired-goto-subdir dir)
  567.                   (dired-hide-subdir 1))))
  568.           hidden-subdirs)))
  569.   ;; outside of the let scope
  570.   (setq buffer-read-only t))
  571.  
  572. ;; Subroutines of dired-revert
  573. ;; Some of these are also used when inserting subdirs.
  574.  
  575. (defun dired-remember-marks (beg end)
  576.   ;; Return alist of files and their marks, from BEG to END.
  577.   (if selective-display            ; must unhide to make this work.
  578.       (let (buffer-read-only)
  579.     (subst-char-in-region beg end ?\r ?\n)))
  580.   (let (fil chr alist)
  581.     (save-excursion
  582.       (goto-char beg)
  583.       (while (re-search-forward dired-re-mark end t)
  584.     (if (setq fil (dired-get-filename nil t))
  585.         (setq chr (preceding-char)
  586.           alist (cons (cons fil chr) alist)))))
  587.     alist))
  588.  
  589. (defun dired-mark-remembered (alist)
  590.   ;; Mark all files remembered in ALIST.
  591.   (let (elt fil chr)
  592.     (while alist
  593.       (setq elt (car alist)
  594.         alist (cdr alist)
  595.         fil (car elt)
  596.         chr (cdr elt))
  597.       (if (dired-goto-file fil)
  598.       (save-excursion
  599.         (beginning-of-line)
  600.         (delete-char 1)
  601.         (insert chr))))))
  602.  
  603. (defun dired-remember-hidden ()
  604.   (let ((l dired-subdir-alist) dir result)
  605.     (while l
  606.       (setq dir (car (car l))
  607.         l (cdr l))
  608.       (if (dired-subdir-hidden-p dir)
  609.       (setq result (cons dir result))))
  610.     result))
  611.  
  612. (defun dired-insert-old-subdirs (old-subdir-alist)
  613.   ;; Try to insert all subdirs that were displayed before
  614.   (or (string-match "R" dired-actual-switches)
  615.       (let (elt dir)
  616.     (while old-subdir-alist
  617.       (setq elt (car old-subdir-alist)
  618.         old-subdir-alist (cdr old-subdir-alist)
  619.         dir (car elt))
  620.       (condition-case ()
  621.           (dired-insert-subdir dir)
  622.         (error nil))))))
  623.  
  624.  
  625. ;; dired mode key bindings and initialization
  626.  
  627. (defvar dired-mode-map nil "Local keymap for dired-mode buffers.")
  628. (if dired-mode-map
  629.     nil
  630.   ;; Force `f' rather than `e' in the mode doc:
  631.   (fset 'dired-advertised-find-file 'dired-find-file)
  632.   ;; This looks ugly when substitute-command-keys uses C-d instead d:
  633.   ;;  (define-key dired-mode-map "\C-d" 'dired-flag-file-deleted)
  634.  
  635.   (setq dired-mode-map (make-keymap))
  636.   (suppress-keymap dired-mode-map)
  637.   ;; Commands to mark certain categories of files
  638.   (define-key dired-mode-map "#" 'dired-flag-auto-save-files)
  639.   (define-key dired-mode-map "*" 'dired-mark-executables)
  640.   (define-key dired-mode-map "." 'dired-clean-directory)
  641.   (define-key dired-mode-map "/" 'dired-mark-directories)
  642.   (define-key dired-mode-map "@" 'dired-mark-symlinks)
  643.   ;; Upper case keys (except !, c, r) for operating on the marked files
  644.   (define-key dired-mode-map "c" 'dired-do-copy)
  645.   (define-key dired-mode-map "r" 'dired-do-move)
  646.   (define-key dired-mode-map "!" 'dired-do-shell-command)
  647.   (define-key dired-mode-map "B" 'dired-do-byte-compile)
  648.   (define-key dired-mode-map "C" 'dired-do-compress)
  649.   (define-key dired-mode-map "G" 'dired-do-chgrp)
  650.   (define-key dired-mode-map "H" 'dired-do-hardlink)
  651.   (define-key dired-mode-map "L" 'dired-do-load)
  652.   (define-key dired-mode-map "M" 'dired-do-chmod)
  653.   (define-key dired-mode-map "O" 'dired-do-chown)
  654.   (define-key dired-mode-map "P" 'dired-do-print)
  655.   (define-key dired-mode-map "U" 'dired-do-uncompress)
  656.   (define-key dired-mode-map "X" 'dired-do-delete)
  657.   (define-key dired-mode-map "Y" 'dired-do-symlink)
  658.   ;; exceptions to the upper key rule
  659.   (define-key dired-mode-map "D" 'dired-diff)
  660.   (define-key dired-mode-map "W" 'dired-why)
  661.   ;; Tree Dired commands
  662.   (define-key dired-mode-map "\M-\C-?" 'dired-unflag-all-files)
  663.   (define-key dired-mode-map "\M-\C-d" 'dired-tree-down)
  664.   (define-key dired-mode-map "\M-\C-u" 'dired-tree-up)
  665.   (define-key dired-mode-map "\M-\C-n" 'dired-next-subdir)
  666.   (define-key dired-mode-map "\M-\C-p" 'dired-prev-subdir)
  667.   ;; move to marked files
  668.   (define-key dired-mode-map "\M-{" 'dired-prev-marked-file)
  669.   (define-key dired-mode-map "\M-}" 'dired-next-marked-file)
  670.   ;; kill marked files
  671.   (define-key dired-mode-map "\M-k" 'dired-do-kill)
  672.   ;; Make all regexp commands share a `%' prefix:
  673.   (fset 'dired-regexp-prefix (make-sparse-keymap))
  674.   (define-key dired-mode-map "%" 'dired-regexp-prefix)
  675.   (define-key dired-mode-map "%u" 'dired-upcase)
  676.   (define-key dired-mode-map "%l" 'dired-downcase)
  677.   (define-key dired-mode-map "%d" 'dired-flag-regexp-files)
  678.   (define-key dired-mode-map "%m" 'dired-mark-files-regexp)
  679.   (define-key dired-mode-map "%r" 'dired-do-rename-regexp)
  680.   (define-key dired-mode-map "%c" 'dired-do-copy-regexp)
  681.   (define-key dired-mode-map "%H" 'dired-do-hardlink-regexp)
  682.   (define-key dired-mode-map "%Y" 'dired-do-symlink-regexp)
  683.   ;; Lower keys for commands not operating on all the marked files
  684.   (define-key dired-mode-map "d" 'dired-flag-file-deleted)
  685.   (define-key dired-mode-map "e" 'dired-find-file)
  686.   (define-key dired-mode-map "f" 'dired-advertised-find-file)
  687.   (define-key dired-mode-map "g" 'revert-buffer)
  688.   (define-key dired-mode-map "h" 'describe-mode)
  689.   (define-key dired-mode-map "i" 'dired-maybe-insert-subdir)
  690.   (define-key dired-mode-map "k" 'dired-kill-line-or-subdir)
  691.   (define-key dired-mode-map "l" 'dired-do-redisplay)
  692.   (define-key dired-mode-map "m" 'dired-mark-subdir-or-file)
  693.   (define-key dired-mode-map "n" 'dired-next-line)
  694.   (define-key dired-mode-map "o" 'dired-find-file-other-window)
  695.   (define-key dired-mode-map "p" 'dired-previous-line)
  696.   (define-key dired-mode-map "q" 'dired-quit)
  697.   (define-key dired-mode-map "s" 'dired-sort-toggle-or-edit)
  698.   (define-key dired-mode-map "u" 'dired-unmark-subdir-or-file)
  699.   (define-key dired-mode-map "v" 'dired-view-file)
  700.   (define-key dired-mode-map "x" 'dired-do-deletions)
  701.   (define-key dired-mode-map "~" 'dired-flag-backup-files)
  702.   (define-key dired-mode-map "\M-~" 'dired-backup-diff)
  703.   (define-key dired-mode-map "+" 'dired-create-directory)
  704.   ;; moving
  705.   (define-key dired-mode-map "<" 'dired-prev-dirline)
  706.   (define-key dired-mode-map ">" 'dired-next-dirline)
  707.   (define-key dired-mode-map "^" 'dired-up-directory)
  708.   (define-key dired-mode-map " "  'dired-next-line)
  709.   (define-key dired-mode-map "\C-n" 'dired-next-line)
  710.   (define-key dired-mode-map "\C-p" 'dired-previous-line)
  711.   ;; hiding
  712.   (define-key dired-mode-map "$" 'dired-hide-subdir)
  713.   (define-key dired-mode-map "=" 'dired-hide-all)
  714.   ;; misc
  715.   (define-key dired-mode-map "?" 'dired-summary)
  716.   (define-key dired-mode-map "\177" 'dired-backup-unflag)
  717.   (define-key dired-mode-map "\C-_" 'dired-undo)
  718.   (define-key dired-mode-map "\C-xu" 'dired-undo)
  719.   )
  720.  
  721. (or (equal (assq 'dired-sort-mode minor-mode-alist)
  722.        '(dired-sort-mode dired-sort-mode))
  723.     ;; Test whether this has already been done in case dired is reloaded
  724.     ;; There may be several elements with dired-sort-mode as car.
  725.     (setq minor-mode-alist
  726.       (cons '(dired-sort-mode dired-sort-mode)
  727.         ;; dired-sort-mode is nil outside dired
  728.         minor-mode-alist)))
  729.  
  730. ;; Dired mode is suitable only for specially formatted data.
  731. (put 'dired-mode 'mode-class 'special)
  732.  
  733. (defun dired-mode (&optional dirname switches)
  734.   "\
  735. Mode for \"editing\" directory listings.
  736. In dired, you are \"editing\" a list of the files in a directory and
  737.   \(optionally) its subdirectories, in the format of `ls -lR'.
  738.   Each directory is a page: use \\[backward-page] and \\[forward-page] to move pagewise.
  739. \"Editing\" means that you can run shell commands on files, visit,
  740.   compress, load or byte-compile them, change their file attributes
  741.   and insert subdirectories into the same buffer.  You can \"mark\"
  742.   files for later commands or \"flag\" them for deletion, either file
  743.   by file or all files matching certain criteria.
  744. You can move using the usual cursor motion commands.\\<dired-mode-map>
  745. Letters no longer insert themselves.  Digits are prefix arguments.
  746. Instead, type \\[dired-flag-file-deleted] to flag a file for Deletion.
  747. Type \\[dired-mark-subdir-or-file] to Mark a file or subdirectory for later commands.
  748.   Most commands operate on the marked files and use the current file
  749.   if no files are marked.  Use a numeric prefix argument to operate on
  750.   the next ARG (or previous -ARG if ARG<0) files, or just `1'
  751.   to operate on the current file only.  Prefix arguments override marks.
  752.   Mark-using commands display a list of failures afterwards.  Type \\[dired-why] to see
  753.   why something went wrong.
  754. Type \\[dired-unmark-subdir-or-file] to Unmark a file or all files of a subdirectory.
  755. Type \\[dired-backup-unflag] to back up one line and unflag.
  756. Type \\[dired-do-deletions] to eXecute the deletions requested.
  757. Type \\[dired-advertised-find-file] to Find the current line's file
  758.   (or dired it in another buffer, if it is a directory).
  759. Type \\[dired-find-file-other-window] to find file or dired directory in Other window.
  760. Type \\[dired-maybe-insert-subdir] to Insert a subdirectory in this buffer.
  761. Type \\[dired-do-move] to Rename a file or move the marked files to another directory.
  762. Type \\[dired-do-copy] to Copy files.
  763. Type \\[dired-sort-toggle-or-edit] to toggle sorting by name/date or change the ls switches.
  764. Type \\[revert-buffer] to read all currently expanded directories again.
  765.   This retains all marks and hides subdirs again that were hidden before.
  766. SPC and DEL can be used to move down and up by lines.
  767.  
  768. If dired ever gets confused, you can either type \\[revert-buffer] \
  769. to read the
  770. directories again, type \\[dired-do-redisplay] \
  771. to relist a single or the marked files or a
  772. subdirectory, or type \\[dired-build-subdir-alist] to parse the buffer
  773. again for the directory tree.
  774.  
  775. Customization variables (rename this buffer and type \\[describe-variable] on each line
  776. for more info):
  777.  
  778.   dired-listing-switches
  779.   dired-trivial-filenames
  780.   dired-shrink-to-fit
  781.   dired-marker-char
  782.   dired-del-marker
  783.   dired-keep-marker-move
  784.   dired-keep-marker-copy
  785.   dired-keep-marker-hardlink
  786.   dired-keep-marker-symlink
  787.  
  788. Hooks (use \\[describe-variable] to see their documentation):
  789.  
  790.   dired-before-readin-hook
  791.   dired-after-readin-hook
  792.   dired-mode-hook
  793.   dired-load-hook
  794.  
  795. Keybindings:
  796. \\{dired-mode-map}"
  797.   ;; Not to be called interactively (e.g. dired-directory will be set
  798.   ;; to default-directory, which is wrong with wildcards).
  799.   (kill-all-local-variables)
  800.   (use-local-map dired-mode-map)
  801.   (dired-advertise)            ; default-directory is already set
  802.   (setq major-mode 'dired-mode
  803.     mode-name "Dired"
  804.     case-fold-search nil
  805.     buffer-read-only t
  806.     selective-display t        ; for subdirectory hiding
  807.     mode-line-buffer-identification '("Dired: %17b"))
  808.   (set (make-local-variable 'revert-buffer-function)
  809.        (function dired-revert))
  810.   (set (make-local-variable 'page-delimiter)
  811.        "\n\n")
  812.   (set (make-local-variable 'dired-directory)
  813.        (or dirname default-directory))
  814.   (set (make-local-variable 'list-buffers-directory)
  815.        dired-directory)
  816.   (set (make-local-variable 'dired-actual-switches)
  817.        (or switches dired-listing-switches))
  818.   (make-local-variable 'dired-sort-mode)
  819.   (dired-sort-other dired-actual-switches t)
  820.   (run-hooks 'dired-mode-hook))
  821.  
  822.  
  823. (defun dired-check-ls-l ()
  824.   (let (case-fold-search)
  825.     (or (string-match "l" dired-actual-switches)
  826.     (error "Dired needs -l in ls switches"))))
  827.  
  828. (defun dired-repeat-over-lines (arg function)
  829.   ;; This version skips non-file lines.
  830.   (beginning-of-line)
  831.   (while (and (> arg 0) (not (eobp)))
  832.     (setq arg (1- arg))
  833.     (beginning-of-line)
  834.     (while (and (not (eobp)) (dired-between-files)) (forward-line 1))
  835.     (save-excursion (funcall function))
  836.     (forward-line 1))
  837.   (while (and (< arg 0) (not (bobp)))
  838.     (setq arg (1+ arg))
  839.     (forward-line -1)
  840.     (while (and (not (bobp)) (dired-between-files)) (forward-line -1))
  841.     (beginning-of-line)
  842.     (save-excursion (funcall function))
  843.     (dired-move-to-filename))
  844.   (dired-move-to-filename))
  845.  
  846. (defun dired-flag-file-deleted (arg)
  847.   "In dired, flag the current line's file for deletion.
  848. With prefix arg, repeat over several lines.
  849.  
  850. If on a subdir headerline, mark all its files except `.' and `..'."
  851.   (interactive "P")
  852.   (let ((dired-marker-char dired-del-marker))
  853.     (dired-mark-subdir-or-file arg)))
  854.  
  855. (defun dired-quit ()
  856.   "Bury the current dired buffer."
  857.   (interactive)
  858.   (bury-buffer))
  859.  
  860. (defun dired-summary ()
  861.   (interactive)
  862.   ;>> this should check the key-bindings and use substitute-command-keys if non-standard
  863.   (message
  864.    "d-elete, u-ndelete, x-punge, f-ind, o-ther window, r-ename, c-opy, h-elp"))
  865.  
  866. (defun dired-create-directory (directory)
  867.   "Create a directory called DIRECTORY."
  868.   (interactive
  869.    (list (read-file-name "Create directory: " (dired-current-directory))))
  870.   (let ((expanded (directory-file-name (expand-file-name directory))))
  871.     (make-directory expanded)
  872.     (dired-add-file expanded)
  873.     (dired-move-to-filename)))
  874.  
  875. (defun dired-undo ()
  876.   "Undo in a dired buffer.
  877. This doesn't recover lost files, it is just normal undo with temporarily
  878. writeable buffer.  You can use it to recover marks, killed lines or subdirs.
  879. In the latter case, you have to do \\[dired-build-subdir-alist] to
  880. parse the buffer again."
  881.   (interactive)
  882.   (let (buffer-read-only)
  883.     (undo)))
  884.  
  885. (defun dired-unflag (arg)
  886.   "In dired, remove the current line's delete flag then move to next line.
  887. Optional prefix ARG says how many lines to unflag."
  888.   (interactive "p")
  889.   (dired-repeat-over-lines arg
  890.     '(lambda ()
  891.        (let (buffer-read-only)
  892.      (delete-char 1)
  893.      (insert " ")
  894.      (forward-char -1)
  895.      nil))))
  896.  
  897. (defun dired-backup-unflag (arg)
  898.   "In dired, move up lines and remove deletion flag there.
  899. Optional prefix ARG says how many lines to unflag; default is one line."
  900.   (interactive "p")
  901.   (dired-unflag (- arg)))
  902.  
  903. (defun dired-next-line (arg)
  904.   "Move down lines then position at filename.
  905. Optional prefix ARG says how many lines to move; default is one line."
  906.   (interactive "p")
  907.   (next-line arg)
  908.   (dired-move-to-filename))
  909.  
  910. (defun dired-previous-line (arg)
  911.   "Move up lines then position at filename.
  912. Optional prefix ARG says how many lines to move; default is one line."
  913.   (interactive "p")
  914.   (previous-line arg)
  915.   (dired-move-to-filename))
  916.  
  917. (defun dired-up-directory ()
  918.   "Run dired on parent directory of current directory.
  919. Find the parent directory either in this buffer or another buffer.
  920. Creates a buffer if necessary."
  921.   (interactive)
  922.   (let* ((dir (dired-current-directory))
  923.      (up (file-name-directory (directory-file-name dir))))
  924.     (or (dired-goto-file (directory-file-name dir))
  925.     (dired-goto-subdir up)
  926.     (progn
  927.       (dired up)
  928.       (dired-goto-file dir)))))
  929.  
  930. (defun dired-find-file ()
  931.   "In dired, visit the file or directory named on this line."
  932.   (interactive)
  933.   (find-file (dired-get-filename)))
  934.  
  935. (defun dired-view-file ()
  936.   "In dired, examine a file in view mode, returning to dired when done.
  937. When file is a directory, show it in this buffer if it is inserted;
  938. otherwise, display it in another buffer."
  939.   (interactive)
  940.   (if (file-directory-p (dired-get-filename))
  941.       (or (dired-goto-subdir (dired-get-filename))
  942.       (dired (dired-get-filename)))
  943.     (view-file (dired-get-filename))))
  944.  
  945. (defun dired-find-file-other-window ()
  946.   "In dired, visit this file or directory in another window."
  947.   (interactive)
  948.   (find-file-other-window (dired-get-filename)))
  949.  
  950. (defun dired-get-filename (&optional localp no-error-if-not-filep)
  951.   "In dired, return name of file mentioned on this line.
  952. Value returned normally includes the directory name.
  953. Optional arg LOCALP with value `no-dir' means don't include directory
  954.   name in result.  A value of t means use path name relative to
  955.   `default-directory', which still may contain slashes if in a subdirectory.
  956. Optional arg NO-ERROR-IF-NOT-FILEP means return nil if no filename on
  957.   this line, otherwise an error occurs."
  958.   (let (case-fold-search file p1 p2)
  959.     (save-excursion
  960.       (if (setq p1 (dired-move-to-filename (not no-error-if-not-filep)))
  961.       (setq p2 (dired-move-to-end-of-filename no-error-if-not-filep))))
  962.     ;; nil if no file on this line, but no-error-if-not-filep is t:
  963.     (if (setq file (and p1 p2 (buffer-substring p1 p2)))
  964.     ;; Check if ls quoted the names, and unquote them.
  965.     ;; Using read to unquote is much faster than substituting
  966.     ;; \007 (4 chars) -> ^G  (1 char) etc. in a lisp loop.
  967.     (cond ((string-match "b" dired-actual-switches) ; System V ls
  968.            ;; This case is about 20% slower than without -b.
  969.            (setq file
  970.              (read
  971.               (concat "\""
  972.                   ;; some ls -b don't escape quotes, argh!
  973.                   ;; This is not needed for GNU ls, though.
  974.                   (or (dired-string-replace-match
  975.                    "\\([^\\]\\)\"" file "\\1\\\\\"")
  976.                   file)
  977.                   "\""))))
  978.           ;; If you do this, update dired-insert-subdir-validate too
  979.           ;; ((string-match "Q" dired-actual-switches) ; GNU ls
  980.           ;;  (setq file (read file)))
  981.           ))
  982.     (if (eq localp 'no-dir)
  983.     file
  984.       (and file (concat (dired-current-directory localp) file)))))
  985.  
  986. (defun dired-move-to-filename (&optional raise-error eol)
  987.   "In dired, move to first char of filename on this line.
  988. Returns position (point) or nil if no filename on this line."
  989.   ;; This is the UNIX version.
  990.   (or eol (setq eol (progn (end-of-line) (point))))
  991.   (beginning-of-line)
  992.   (if (string-match "l" dired-actual-switches)
  993.       (if (re-search-forward
  994.        "\\(Jan\\|Feb\\|Mar\\|Apr\\|May\\|Jun\\|Jul\\|Aug\\|Sep\\|Oct\\|Nov\\|Dec\\)[ ]+[0-9]+"
  995.        eol t)
  996.       (progn
  997.         (skip-chars-forward " ")    ; there is one SPC after day of month
  998.         (skip-chars-forward "^ " eol) ; move after time of day (or year)
  999.         (skip-chars-forward " " eol) ; there is space before the file name
  1000.         ;; Actually, if the year instead of clock time is displayed,
  1001.         ;; there are (only for some ls programs?) two spaces instead
  1002.         ;; of one before the name.
  1003.         ;; If we could depend on ls inserting exactly one SPC we
  1004.         ;; would not bomb on names _starting_ with SPC.
  1005.         (point))
  1006.     (if raise-error
  1007.         (error "No file on this line")
  1008.       nil))
  1009.     ;; else ls switches don't contain -l.
  1010.     ;; Note that even if we make dired-move-to-filename and
  1011.     ;; dired-move-to-end-of-filename (and thus dired-get-filename)
  1012.     ;; work, all commands that gleaned information from the permission
  1013.     ;; bits (like dired-mark-directories) will cease to work properly.
  1014.     (if (eolp)
  1015.     (if raise-error
  1016.         (error "No file on this line")
  1017.       nil)
  1018.       ;; skip marker, if any
  1019.       (forward-char))
  1020.     (skip-chars-forward " ")
  1021.     (point)))
  1022.  
  1023. (defun dired-move-to-end-of-filename (&optional no-error)
  1024.   ;; Assumes point is at beginning of filename,
  1025.   ;; thus the rwx bit re-search-backward below will succeed in *this*
  1026.   ;; line if at all.  So, it should be called only after
  1027.   ;; (dired-move-to-filename t).
  1028.   ;; On failure, signals an error (with non-nil NO-ERROR just returns nil).
  1029.   ;; This is the UNIX version.
  1030.   (let (opoint file-type executable symlink hidden case-fold-search used-F eol)
  1031.     ;; case-fold-search is nil now, so we can test for capital F:
  1032.     (setq used-F (string-match "F" dired-actual-switches)
  1033.       opoint (point)
  1034.           eol (save-excursion (end-of-line) (point))
  1035.       hidden (and selective-display
  1036.               (save-excursion (search-forward "\r" eol t))))
  1037.     (if hidden
  1038.     nil
  1039.       (save-excursion;; Find out what kind of file this is:
  1040.     ;; Restrict perm bits to be non-blank,
  1041.     ;; otherwise this matches one char to early (looking backward):
  1042.     ;; "l---------" (some systems make symlinks that way)
  1043.     ;; "----------" (plain file with zero perms)
  1044.     (if (re-search-backward
  1045.          "\\([^ ]\\)[-r][-w]\\([^ ]\\)[-r][-w]\\([^ ]\\)[-r][-w]\\([^ ]\\)"
  1046.          nil t)
  1047.         (setq file-type (char-after (match-beginning 1))
  1048.           symlink (eq file-type ?l)
  1049.           ;; Only with -F we need to know whether it's an executable
  1050.           executable (and
  1051.                   used-F
  1052.                   (string-match
  1053.                    "[xst]";; execute bit set anywhere?
  1054.                    (concat
  1055.                 (buffer-substring (match-beginning 2)
  1056.                           (match-end 2))
  1057.                 (buffer-substring (match-beginning 3)
  1058.                           (match-end 3))
  1059.                 (buffer-substring (match-beginning 4)
  1060.                           (match-end 4))))))
  1061.       (or no-error
  1062.           (not (string-match "l" dired-actual-switches))
  1063.           (error "No file on this line"))))
  1064.       ;; Move point to end of name:
  1065.       (if symlink
  1066.       (if (search-forward " ->" eol t)
  1067.           (progn
  1068.         (forward-char -3)
  1069.         (and used-F
  1070.              dired-ls-F-marks-symlinks
  1071.              (eq (preceding-char) ?@);; did ls really mark the link?
  1072.              (forward-char -1))))
  1073.     (goto-char eol);; else not a symbolic link
  1074.     ;; ls -lF marks dirs, sockets and executables with exactly one
  1075.     ;; trailing character. (Executable bits on symlinks ain't mean
  1076.     ;; a thing, even to ls, but we know it's not a symlink.)
  1077.     (and used-F
  1078.          ;; -F may not actually be honored, e.g. by an FTP ls in ange-ftp
  1079.          (let ((char (preceding-char)))
  1080.            (or (and (eq file-type ?d) (eq char ?/))
  1081.            (and executable (eq char ?*))
  1082.            (and (eq file-type ?s) (eq char ?=))))
  1083.          (forward-char -1))))
  1084.     (or no-error
  1085.     (not (eq opoint (point)))
  1086.     (error (if hidden
  1087.            (substitute-command-keys
  1088.             "File line is hidden, type \\[dired-hide-subdir] to unhide")
  1089.          "No file on this line")))
  1090.     (if (eq opoint (point))
  1091.     nil
  1092.       (point))))
  1093.  
  1094.  
  1095. ;; Perhaps something could be done to handle VMS' own backups.
  1096.  
  1097. (defun dired-clean-directory (keep)
  1098.   "Flag numerical backups for deletion.
  1099. Spares `dired-kept-versions' latest versions, and `kept-old-versions' oldest.
  1100. Positive prefix arg KEEP overrides `dired-kept-versions';
  1101. Negative prefix arg KEEP overrides `kept-old-versions' with KEEP made positive.
  1102.  
  1103. To clear the flags on these files, you can use \\[dired-flag-backup-files]
  1104. with a prefix argument."
  1105.   (interactive "P")
  1106.   (setq keep (if keep (prefix-numeric-value keep) dired-kept-versions))
  1107.   (let ((early-retention (if (< keep 0) (- keep) kept-old-versions))
  1108.     (late-retention (if (<= keep 0) dired-kept-versions keep))
  1109.     (file-version-assoc-list ()))
  1110.     (message "Cleaning numerical backups (keeping %d late, %d old)..."
  1111.          late-retention early-retention)
  1112.     ;; Look at each file.
  1113.     ;; If the file has numeric backup versions,
  1114.     ;; put on file-version-assoc-list an element of the form
  1115.     ;; (FILENAME . VERSION-NUMBER-LIST)
  1116.     (dired-map-dired-file-lines (function dired-collect-file-versions))
  1117.     ;; Sort each VERSION-NUMBER-LIST,
  1118.     ;; and remove the versions not to be deleted.
  1119.     (let ((fval file-version-assoc-list))
  1120.       (while fval
  1121.     (let* ((sorted-v-list (cons 'q (sort (cdr (car fval)) '<)))
  1122.            (v-count (length sorted-v-list)))
  1123.       (if (> v-count (+ early-retention late-retention))
  1124.           (rplacd (nthcdr early-retention sorted-v-list)
  1125.               (nthcdr (- v-count late-retention)
  1126.                   sorted-v-list)))
  1127.       (rplacd (car fval)
  1128.           (cdr sorted-v-list)))
  1129.     (setq fval (cdr fval))))
  1130.     ;; Look at each file.  If it is a numeric backup file,
  1131.     ;; find it in a VERSION-NUMBER-LIST and maybe flag it for deletion.
  1132.     (dired-map-dired-file-lines (function dired-trample-file-versions))
  1133.     (message "Cleaning numerical backups...done")))
  1134.  
  1135. ;;; Subroutines of dired-clean-directory.
  1136.  
  1137. (defun dired-map-dired-file-lines (fun)
  1138.   ;; Perform FUN with point at the end of each non-directory line.
  1139.   ;; FUN takes one argument, the filename (complete pathname).
  1140.   (dired-check-ls-l)
  1141.   (save-excursion
  1142.     (let (file buffer-read-only)
  1143.       (goto-char (point-min))
  1144.       (while (not (eobp))
  1145.     (save-excursion
  1146.       (and (not (looking-at dired-re-dir))
  1147.            (not (eolp))
  1148.            (setq file (dired-get-filename nil t)) ; nil on non-file
  1149.            (progn (end-of-line)
  1150.               (funcall fun file))))
  1151.     (forward-line 1)))))
  1152.  
  1153. (defun dired-collect-file-versions (fn)
  1154.   ;;  "If it looks like file FN has versions, return a list of the versions.
  1155.   ;;That is a list of strings which are file names.
  1156.   ;;The caller may want to flag some of these files for deletion."
  1157.     (let* ((base-versions
  1158.         (concat (file-name-nondirectory fn) ".~"))
  1159.        (bv-length (length base-versions))
  1160.        (possibilities (file-name-all-completions
  1161.                base-versions
  1162.                (file-name-directory fn)))
  1163.        (versions (mapcar 'backup-extract-version possibilities)))
  1164.       (if versions
  1165.       (setq file-version-assoc-list (cons (cons fn versions)
  1166.                           file-version-assoc-list)))))
  1167.  
  1168. (defun dired-trample-file-versions (fn)
  1169.   (let* ((start-vn (string-match "\\.~[0-9]+~$" fn))
  1170.      base-version-list)
  1171.     (and start-vn
  1172.      (setq base-version-list    ; there was a base version to which
  1173.            (assoc (substring fn 0 start-vn)    ; this looks like a
  1174.               file-version-assoc-list))    ; subversion
  1175.      (not (memq (string-to-int (substring fn (+ 2 start-vn)))
  1176.             base-version-list))    ; this one doesn't make the cut
  1177.      (progn (beginning-of-line)
  1178.         (delete-char 1)
  1179.         (insert dired-del-marker)))))
  1180.  
  1181.  
  1182. ;; Keeping Dired buffers in sync with the filesystem and with each other
  1183.  
  1184. (defvar dired-buffers nil
  1185.   ;; Enlarged by dired-advertise
  1186.   ;; Queried by function dired-buffers-for-dir. When this detects a
  1187.   ;; killed buffer, it is removed from this list.
  1188.   "Alist of directories and their associated dired buffers.")
  1189.  
  1190. (defun dired-buffers-for-dir (dir)
  1191. ;; Return a list of buffers that dired DIR (top level or in-situ subdir).
  1192. ;; The list is in reverse order of buffer creation, most recent last.
  1193. ;; As a side effect, killed dired buffers for DIR are removed from
  1194. ;; dired-buffers.
  1195.   (setq dir (file-name-as-directory dir))
  1196.   (let ((alist dired-buffers) result elt)
  1197.     (while alist
  1198.       (setq elt (car alist))
  1199.       (if (dired-in-this-tree dir (car elt))
  1200.       (let ((buf (cdr elt)))
  1201.         (if (buffer-name buf)
  1202.         (if (assoc dir (save-excursion
  1203.                  (set-buffer buf)
  1204.                  dired-subdir-alist))
  1205.             (setq result (cons buf result)))
  1206.           ;; else buffer is killed - clean up:
  1207.           (setq dired-buffers (delq elt dired-buffers)))))
  1208.       (setq alist (cdr alist)))
  1209.     result))
  1210.  
  1211. (defun dired-advertise ()
  1212.   ;;"Advertise in variable `dired-buffers' that we dired `default-directory'."
  1213.   ;; With wildcards we actually advertise too much.
  1214.   (if (memq (current-buffer) (dired-buffers-for-dir default-directory))
  1215.       t                    ; we have already advertised ourselves
  1216.     (setq dired-buffers
  1217.       (cons (cons default-directory (current-buffer))
  1218.         dired-buffers))))
  1219.  
  1220. (defun dired-unadvertise (dir)
  1221.   ;; Remove DIR from the buffer alist in variable dired-buffers.
  1222.   ;; This has the effect of removing any buffer whose main directory is DIR.
  1223.   ;; It does not affect buffers in which DIR is a subdir.
  1224.   ;; Removing is also done as a side-effect in dired-buffer-for-dir.
  1225.   (setq dired-buffers
  1226.       (delq (assoc dir dired-buffers) dired-buffers)))
  1227.  
  1228. (defun dired-fun-in-all-buffers (directory fun &rest args)
  1229.   ;; In all buffers dired'ing DIRECTORY, run FUN with ARGS.
  1230.   ;; Return list of buffers where FUN succeeded (i.e., returned non-nil).
  1231.   (let ((buf-list (dired-buffers-for-dir directory))
  1232.     (obuf (current-buffer))
  1233.     buf success-list)
  1234.     (while buf-list
  1235.       (setq buf (car buf-list)
  1236.         buf-list (cdr buf-list))
  1237.       (unwind-protect
  1238.       (progn
  1239.         (set-buffer buf)
  1240.         (if (apply fun args)
  1241.         (setq success-list (cons (buffer-name buf) success-list))))
  1242.     (set-buffer obuf)))
  1243.     success-list))
  1244.  
  1245. (defun dired-add-file (filename &optional marker-char)
  1246.   (dired-fun-in-all-buffers
  1247.    (file-name-directory filename)
  1248.    (function dired-add-entry) filename marker-char))
  1249.  
  1250. (defun dired-add-entry (filename &optional marker-char)
  1251.   ;; Add a new entry for FILENAME, optionally marking it
  1252.   ;; with MARKER-CHAR (a character, else dired-marker-char is used).
  1253.   ;; Note that this adds the entry `out of order' if files sorted by
  1254.   ;; time, etc.
  1255.   ;; At least this version inserts in the right subdirectory (if present).
  1256.   ;; And it skips "." or ".." (see `dired-trivial-filenames').
  1257.   ;; Hidden subdirs are exposed if a file is added there.
  1258.   (setq filename (directory-file-name filename))
  1259.   ;; Entry is always for files, even if they happen to also be directories
  1260.   (let ((opoint (point))
  1261.     (cur-dir (dired-current-directory))
  1262.     (directory (file-name-directory filename))
  1263.     reason)
  1264.     (setq filename (file-name-nondirectory filename)
  1265.       reason
  1266.       (catch 'not-found
  1267.         (if (string= directory cur-dir)
  1268.         (progn
  1269.           (if (dired-subdir-hidden-p cur-dir)
  1270.               (dired-unhide-subdir))
  1271.           ;; We are already where we should be, except when
  1272.           ;; point is before the subdir line or its total line.
  1273.           (let ((p (dired-after-subdir-garbage cur-dir)))
  1274.             (if (< (point) p)
  1275.             (goto-char p))))
  1276.           ;; else try to find correct place to insert
  1277.           (if (dired-goto-subdir directory)
  1278.           (progn;; unhide if necessary
  1279.             (if (looking-at "\r");; point is at end of subdir line
  1280.             (dired-unhide-subdir))
  1281.             ;; found - skip subdir and `total' line
  1282.             ;; and uninteresting files like . and ..
  1283.             ;; This better not moves into the next subdir!
  1284.             (dired-goto-next-nontrivial-file))
  1285.         ;; not found
  1286.         (throw 'not-found "Subdir not found")))
  1287.         ;; found and point is at The Right Place:
  1288.         (let (buffer-read-only)
  1289.           (beginning-of-line)
  1290.           (dired-add-entry-do-indentation marker-char)
  1291.           (dired-ls (dired-make-absolute filename directory);; don't expand `.' !
  1292.             (concat dired-actual-switches "d"))
  1293.           (forward-line -1)
  1294.           ;; We want to have the non-directory part, only:
  1295.           (let* ((beg (dired-move-to-filename t)) ; error for strange output
  1296.              (end (dired-move-to-end-of-filename)))
  1297.         (setq filename (buffer-substring beg end))
  1298.         (delete-region beg end)
  1299.         (insert (file-name-nondirectory filename)))
  1300.           (if dired-after-readin-hook;; the subdir-alist is not affected...
  1301.           (save-excursion;; ...so we can run it right now:
  1302.             (save-restriction
  1303.               (beginning-of-line)
  1304.               (narrow-to-region (point) (save-excursion
  1305.                           (forward-line 1) (point)))
  1306.               (run-hooks 'dired-after-readin-hook))))
  1307.           (dired-move-to-filename))
  1308.         ;; return nil if all went well
  1309.         nil))
  1310.     (if reason                ; don't move away on failure
  1311.     (goto-char opoint))
  1312.     (not reason)))            ; return t on succes, nil else
  1313.  
  1314. ;; This is a separate function for the sake of nested dired format.
  1315. (defun dired-add-entry-do-indentation (marker-char)
  1316.   ;; two spaces or a marker plus a space:
  1317.   (insert (if marker-char
  1318.           (if (integerp marker-char) marker-char dired-marker-char)
  1319.         ?\040)
  1320.       ?\040))
  1321.  
  1322. (defun dired-after-subdir-garbage (dir)
  1323.   ;; Return pos of first file line of DIR, skipping header and total
  1324.   ;; or wildcard lines.
  1325.   ;; Important: never moves into the next subdir.
  1326.   ;; DIR is assumed to be unhidden.
  1327.   ;; Will probably be redefined for VMS etc.
  1328.   (save-excursion
  1329.     (or (dired-goto-subdir dir) (error "This cannot happen"))
  1330.     (forward-line 1)
  1331.     (while (and (not (eolp))        ; don't cross subdir boundary
  1332.         (not (dired-move-to-filename)))
  1333.     (forward-line 1))
  1334.     (point)))
  1335.  
  1336. (defun dired-remove-file (file)
  1337.   (dired-fun-in-all-buffers
  1338.    (file-name-directory file) (function dired-remove-entry) file))
  1339.  
  1340. (defun dired-remove-entry (file)
  1341.   (save-excursion
  1342.     (and (dired-goto-file file)
  1343.      (let (buffer-read-only)
  1344.        (delete-region (progn (beginning-of-line) (point))
  1345.               (save-excursion (forward-line 1) (point)))))))
  1346.  
  1347. (defun dired-relist-file (file)
  1348.   (dired-fun-in-all-buffers (file-name-directory file)
  1349.                 (function dired-relist-entry) file))
  1350.  
  1351. (defun dired-relist-entry (file)
  1352.   ;; Relist the line for FILE, or just add it if it did not exist.
  1353.   ;; FILE must be an absolute pathname.
  1354.   (let (buffer-read-only marker)
  1355.     ;; If cursor is already on FILE's line delete-region will cause
  1356.     ;; save-excursion to fail because of floating makers,
  1357.     ;; moving point to beginning of line.  Sigh.
  1358.     (save-excursion
  1359.       (and (dired-goto-file file)
  1360.        (delete-region (progn (beginning-of-line)
  1361.                  (setq marker (following-char))
  1362.                  (point))
  1363.               (save-excursion (forward-line 1) (point))))
  1364.       (setq file (directory-file-name file))
  1365.       (dired-add-entry file (if (eq ?\040 marker) nil marker)))))
  1366.  
  1367. (defun dired-update-file-line (file)
  1368.   ;; Delete the current line, and insert an entry for FILE.
  1369.   ;; If FILE is nil, then just delete the current line.
  1370.   ;; Keeps any marks that may be present in column one (doing this
  1371.   ;; here is faster than with dired-add-entry's optional arg).
  1372.   ;; Does not update other dired buffers.  Use dired-relist-entry for that.
  1373.   (beginning-of-line)
  1374.   (let ((char (following-char)) (opoint (point)))
  1375.     (delete-region (point) (progn (forward-line 1) (point)))
  1376.     (if file
  1377.     (progn
  1378.       (dired-add-entry file)
  1379.       ;; Replace space by old marker without moving point.
  1380.       ;; Faster than goto+insdel inside a save-excursion?
  1381.       (subst-char-in-region opoint (1+ opoint) ?\040 char))))
  1382.   (dired-move-to-filename))
  1383.  
  1384.  
  1385. ;; Running subprocesses, checking and logging of their errors.
  1386.  
  1387. (defvar dired-log-buf "*Dired log*")
  1388.  
  1389. (defun dired-why ()
  1390.   "Pop up a buffer with error log output from Dired.
  1391. A group of errors from a single command ends with a formfeed.
  1392. Thus, use \\[backward-page] to find the beginning of a group of errors."
  1393.   (interactive)
  1394.   (let ((obuf (current-buffer)))
  1395.     (pop-to-buffer dired-log-buf)
  1396.     (goto-char (point-max))
  1397.     (recenter -1)
  1398.     (switch-to-buffer-other-window obuf)))
  1399.  
  1400. (defun dired-log (log &rest args)
  1401.   ;; Log a message or the contents of a buffer.
  1402.   ;; If LOG is a string and there are more args, it is formatted with
  1403.   ;; those ARGS.  Usually the LOG string ends with a \n.
  1404.   ;; End each bunch of errors with (dired-log t): this inserts
  1405.   ;; current time and buffer, and a \f (formfeed).
  1406.   (let ((obuf (current-buffer)))
  1407.     (unwind-protect            ; want to move point
  1408.     (progn
  1409.       (set-buffer (get-buffer-create dired-log-buf))
  1410.       (goto-char (point-max))
  1411.       (let (buffer-read-only)
  1412.         (cond ((stringp log)
  1413.            (insert (if args
  1414.                    (apply (function format) log args)
  1415.                  log)))
  1416.           ((bufferp log)
  1417.            (insert-buffer log))
  1418.           ((eq t log)
  1419.            (insert "\n\t" (current-time-string)
  1420.                "\tBuffer `" (buffer-name obuf) "'\n\f\n")))))
  1421.       (set-buffer obuf))))
  1422.  
  1423. (defun dired-log-summary (log &rest args)
  1424.   ;; Log a summary describing a bunch of errors.
  1425.   (apply (function dired-log) (concat "\n" log) args)
  1426.   (dired-log t))
  1427.  
  1428. ;; In Emacs 19 this will return program's exit status.
  1429. ;; This is a separate function so that ange-ftp can redefine it.
  1430. (defun dired-call-process (program discard &rest arguments)
  1431. ;  "Run PROGRAM with output to current buffer unless DISCARD is t.
  1432. ;Remaining arguments are strings passed as command arguments to PROGRAM."
  1433.   (apply 'call-process program nil (not discard) nil arguments))
  1434.  
  1435. (defun dired-check-process-checker (exit-status)
  1436.   ;; In Emacs 19, EXIT-STATUS comes from (dired-)call-process
  1437.   ;; Then this function should return (/= 0 exit-status)
  1438.   ;; In Emacs 18 the exit status is not accessible, so we
  1439.   ;; do the following which is not always correct as some compress
  1440.   ;; programs are verbose by default or otherwise braindamaged
  1441.   (if dired-emacs-19-p
  1442.       (/= 0 exit-status);; >>> install (does it work in Emacs 19?)
  1443.     (/= 0 (buffer-size)))        ; run in program's output buffer
  1444.   ;; If have you one of those compress programs, you might
  1445.   ;; want to redefine this function to look closer at compress' output.
  1446.   ;; This is why it is a separate function.
  1447.   )
  1448.  
  1449. (defun dired-check-process (msg program &rest arguments)
  1450. ;  "Display MSG while running PROGRAM, and check for output.
  1451. ;Remaining arguments are strings passed as command arguments to PROGRAM.
  1452. ; On error as determined by dired-check-process-checker, insert output
  1453. ; in a log buffer and return the offending ARGUMENTS or PROGRAM.
  1454. ; Caller can cons up a list of failed args.
  1455. ;Else returns nil for success."
  1456.   (let (err-buffer err (dir default-directory))
  1457.     (message "%s..." msg)
  1458.     (save-excursion
  1459.       ;; Get a clean buffer for error output:
  1460.       (setq err-buffer (get-buffer-create " *dired-check-process output*"))
  1461.       (set-buffer err-buffer)
  1462.       (erase-buffer)
  1463.       (setq default-directory dir    ; caller's default-directory
  1464.         err (dired-check-process-checker
  1465.          (apply (function dired-call-process) program nil arguments)))
  1466.       (if err
  1467.       (progn
  1468.         (dired-log (concat program " " (prin1-to-string arguments) "\n"))
  1469.         (dired-log err-buffer)
  1470.         (or arguments program t))
  1471.     (kill-buffer err-buffer)
  1472.     (message "%s...done" msg)
  1473.     nil))))
  1474.  
  1475. ;;; 7K
  1476. ;;;###begin dired-cmd.el
  1477. ;; Diffing and compressing
  1478.  
  1479. (defun dired-diff (file &optional switches)
  1480.   "Compare file at point with file FILE using `diff'.
  1481. FILE defaults to the file at the mark.
  1482. The prompted-for file is the first file given to `diff'.
  1483. Prefix arg lets you edit the diff switches.  See the command `diff'."
  1484.   (interactive
  1485.    (let ((default (if (mark)
  1486.               (save-excursion (goto-char (mark))
  1487.                       (dired-get-filename t t)))))
  1488.      (list (read-file-name (format "Diff %s with: %s"
  1489.                    (dired-get-filename t)
  1490.                    (if default
  1491.                        (concat "(default " default ") ")
  1492.                      ""))
  1493.                (dired-current-directory) default t)
  1494.        (if (fboundp 'diff-read-switches)
  1495.            (diff-read-switches "Options for diff: ")))))
  1496.   (if switches                ; Emacs 19's diff has but two
  1497.       (diff file (dired-get-filename t) switches) ; args (yet ;-)
  1498.     (diff file (dired-get-filename t))))
  1499.  
  1500. (defun dired-backup-diff (&optional switches)
  1501.   "Diff this file with its backup file or vice versa.
  1502. Uses the latest backup, if there are several numerical backups.
  1503. If this file is a backup, diff it with its original.
  1504. The backup file is the first file given to `diff'.
  1505. Prefix arg lets you edit the diff switches.  See the command `diff'."
  1506.   (interactive (list (if (fboundp 'diff-read-switches)
  1507.              (diff-read-switches "Diff with switches: "))))
  1508.   (let (bak ori (file (dired-get-filename)))
  1509.     (if (backup-file-name-p file)
  1510.     (setq bak file
  1511.           ori (file-name-sans-versions file))
  1512.       (setq bak (or (latest-backup-file file)
  1513.             (error "No backup found for %s" file))
  1514.         ori file))
  1515.     (if switches
  1516.     (diff bak ori switches)
  1517.       (diff bak ori))))
  1518.  
  1519. ;;>>> install (move this function into files.el)
  1520. (defun latest-backup-file (fn)    ; actually belongs into files.el
  1521.   "Return the latest existing backup of FILE, or nil."
  1522.   ;; First try simple backup, then the highest numbered of the
  1523.   ;; numbered backups.
  1524.   ;; Ignore the value of version-control because we look for existing
  1525.   ;; backups, which maybe were made earlier or by another user with
  1526.   ;; a different value of version-control.
  1527.   (setq fn (expand-file-name fn))
  1528.   (or
  1529.    (let ((bak (make-backup-file-name fn)))
  1530.      (if (file-exists-p bak) bak))
  1531.    (let* ((dir (file-name-directory fn))
  1532.       (base-versions (concat (file-name-nondirectory fn) ".~"))
  1533.       (bv-length (length base-versions)))
  1534.      (concat dir
  1535.          (car (sort
  1536.            (file-name-all-completions base-versions dir)
  1537.            ;; bv-length is a fluid var for backup-extract-version:
  1538.            (function
  1539.             (lambda (fn1 fn2)
  1540.               (> (backup-extract-version fn1)
  1541.              (backup-extract-version fn2))))))))))
  1542.  
  1543. ;; This is a separate function for the sake of ange-ftp.el
  1544. (defun dired-compress-make-compressed-filename (from-file &optional reverse)
  1545. ;;  "Converts a filename FROM-FILE to the filename of the associated
  1546. ;;  compressed file.  With an optional argument REVERSE, the reverse
  1547. ;;  conversion is done."
  1548.   (if reverse
  1549.       (substring from-file 0 -2)
  1550.     (concat from-file ".Z")))
  1551.  
  1552. (defun dired-compress ()
  1553.   ;; Compress current file.  Return nil for success, offending filename else.
  1554.   (dired-check-ls-l)
  1555.   (let* (buffer-read-only
  1556.      (from-file (dired-get-filename))
  1557.      (to-file (dired-compress-make-compressed-filename from-file)))
  1558.     (cond ((save-excursion (beginning-of-line)
  1559.                (looking-at dired-re-sym))
  1560.        (dired-log (concat "Attempt to compress a symbolic link:\n"
  1561.                   from-file))
  1562.        (dired-make-relative from-file))
  1563.       ((dired-check-process (concat "Compressing " from-file)
  1564.                 "compress" "-f" from-file)
  1565.        ;; errors from the process are already logged by dired-check-process
  1566.        (dired-make-relative from-file))
  1567.     (t
  1568.      (dired-update-file-line to-file)
  1569.      nil))))
  1570.  
  1571. (defun dired-uncompress ()
  1572.   ;; Uncompress current file.  Return nil for success, offending filename else.
  1573.   (let* (buffer-read-only
  1574.      (from-file (dired-get-filename))
  1575.      (to-file (dired-compress-make-compressed-filename from-file t)))
  1576.     (if (dired-check-process (concat "Uncompressing " from-file)
  1577.                  "uncompress" from-file)
  1578.     (dired-make-relative from-file)
  1579.       (dired-update-file-line to-file)
  1580.       nil)))
  1581.  
  1582. (defun dired-mark-map-check (fun arg op-symbol &optional show-progress)
  1583. ;  "Map FUN over marked files (with second ARG like in dired-mark-map)
  1584. ; and display failures.
  1585.  
  1586. ; FUN takes zero args.  It returns non-nil (the offending object, e.g.
  1587. ; the short form of the filename) for a failure and probably logs a
  1588. ; detailed error explanation using function `dired-log'.
  1589.  
  1590. ; OP-SYMBOL is a symbol describing the operation performed (e.g.
  1591. ; `compress').  It is used with `dired-mark-pop-up' to prompt the user
  1592. ; (e.g. with `Compress * [2 files]? ') and to display errors (e.g.
  1593. ; `Failed to compress 1 of 2 files - type W to see why ("foo")')
  1594.  
  1595. ; SHOW-PROGRESS if non-nil means redisplay dired after each file."
  1596.   (if (dired-mark-confirm op-symbol arg)
  1597.       (let* ((total-list;; all of FUN's return values
  1598.           (dired-mark-map (funcall fun) arg show-progress))
  1599.          (total (length total-list))
  1600.          (failures (delq nil total-list))
  1601.          (count (length failures)))
  1602.     (if (not failures)
  1603.         (message "%s: %d file%s."
  1604.              (capitalize (symbol-name op-symbol))
  1605.              total (dired-plural-s total))
  1606.       (message "Failed to %s %d of %d file%s - type W to see why %s"
  1607.            (symbol-name op-symbol) count total (dired-plural-s total)
  1608.            ;; this gives a short list of failed files in parens
  1609.            ;; which may be sufficient for the user even
  1610.            ;; without typing `W' for the process' diagnostics
  1611.            failures)
  1612.       ;; end this bunch of errors:
  1613.       (dired-log-summary
  1614.        "Failed to %s %d of %d file%s"
  1615.        (symbol-name op-symbol) count total (dired-plural-s total))))))
  1616.  
  1617. (defun dired-do-compress (&optional arg)
  1618.   "Compress marked (or next ARG) files.
  1619. Type \\[dired-do-uncompress] to uncompress again."
  1620.   (interactive "P")
  1621.   (dired-mark-map-check (function dired-compress) arg 'compress t))
  1622.  
  1623. (defun dired-do-uncompress (&optional arg)
  1624.   "Uncompress marked (or next ARG) files."
  1625.   (interactive "P")
  1626.   (dired-mark-map-check (function dired-uncompress) arg 'uncompress t))
  1627.  
  1628. ;; Commands for Emacs Lisp files - load and byte compile
  1629.  
  1630. (defun dired-byte-compile ()
  1631.   ;; Return nil for success, offending file name else.
  1632.   (let* ((filename (dired-get-filename))
  1633.      (elc-file
  1634.       (if (eq system-type 'vax-vms)
  1635.           (concat (substring filename 0 (string-match ";" filename)) "c")
  1636.         (concat filename "c")))
  1637.      buffer-read-only failure)
  1638.     (condition-case err
  1639.     (save-excursion (byte-compile-file filename))
  1640.       (error
  1641.        (setq failure err)))
  1642.     (if failure
  1643.     (progn
  1644.       (dired-log "Byte compile error for %s:\n%s\n" filename failure)
  1645.       (dired-make-relative filename))
  1646.       (dired-remove-file elc-file)
  1647.       (forward-line)            ; insert .elc after its .el file
  1648.       (dired-add-file elc-file)
  1649.       nil)))
  1650.  
  1651. (defun dired-do-byte-compile (&optional arg)
  1652.   "Byte compile marked (or next ARG) Emacs lisp files."
  1653.   (interactive "P")
  1654.   (dired-mark-map-check (function dired-byte-compile) arg 'byte-compile t))
  1655.  
  1656. (defun dired-load ()
  1657.   ;; Return nil for success, offending file name else.
  1658.   (let ((file (dired-get-filename)) failure)
  1659.     (condition-case err
  1660.       (load file nil nil t)
  1661.       (error (setq failure err)))
  1662.     (if (not failure)
  1663.     nil
  1664.       (dired-log "Load error for %s:\n%s\n" file failure)
  1665.       (dired-make-relative file))))
  1666.  
  1667. (defun dired-do-load (&optional arg)
  1668.   "Load the marked (or next ARG) Emacs lisp files."
  1669.   (interactive "P")
  1670.   (dired-mark-map-check (function dired-load) arg 'load t))
  1671.  
  1672. (defun dired-do-chxxx (attribute-name program op-symbol arg)
  1673.   ;; Change file attributes (mode, group, owner) of marked files and
  1674.   ;; refresh their file lines.
  1675.   ;; ATTRIBUTE-NAME is a string describing the attribute to the user.
  1676.   ;; PROGRAM is the program used to change the attribute.
  1677.   ;; OP-SYMBOL is the type of operation (for use in dired-mark-pop-up).
  1678.   ;; ARG describes which files to use, like in dired-mark-get-files.
  1679.   (let* ((files (dired-mark-get-files t arg))
  1680.      (new-attribute
  1681.       (dired-mark-read-string
  1682.        (concat "Change " attribute-name " of %s to: ")
  1683.        nil op-symbol arg files))
  1684.      (operation (concat program " " new-attribute))
  1685.      (failure (apply (function dired-check-process)
  1686.              operation program new-attribute
  1687.              files)))
  1688.     (dired-do-redisplay arg);; moves point if ARG is an integer
  1689.     (if failure
  1690.     (dired-log-summary
  1691.      (message "%s: error - type W to see why." operation)))))
  1692.  
  1693. (defun dired-do-chmod (&optional arg)
  1694.   "Change the mode of the marked (or next ARG) files.
  1695. This calls chmod, thus symbolic modes like `g+w' are allowed."
  1696.   (interactive "P")
  1697.   (dired-do-chxxx "Mode" "chmod" 'chmod arg))
  1698.  
  1699. (defun dired-do-chgrp (&optional arg)
  1700.   "Change the group of the marked (or next ARG) files."
  1701.   (interactive "P")
  1702.   (dired-do-chxxx "Group" "chgrp" 'chgrp arg))
  1703.  
  1704. (defun dired-do-chown (&optional arg)
  1705.   "Change the owner of the marked (or next ARG) files."
  1706.   (interactive "P")
  1707.   (dired-do-chxxx "Owner" dired-chown-program 'chown arg))
  1708.  
  1709. ;;;###end dired-cmd.el
  1710.  
  1711.  
  1712. ;; Deleting files
  1713.  
  1714. (defun dired-do-deletions ()
  1715.   "In dired, delete the files flagged for deletion."
  1716.   (interactive)
  1717.   (let* ((dired-marker-char dired-del-marker)
  1718.      (regexp (dired-marker-regexp))
  1719.      case-fold-search)
  1720.     (if (save-excursion (goto-char (point-min))
  1721.             (re-search-forward regexp nil t))
  1722.     (dired-internal-do-deletions
  1723.      ;; this can't move point since ARG is nil
  1724.      (dired-mark-map (cons (dired-get-filename) (point))
  1725.              nil)
  1726.      nil)
  1727.       (message "(No deletions requested)"))))
  1728.  
  1729. (defun dired-do-delete (&optional arg)
  1730.   "Delete all marked (or next ARG) files."
  1731.   ;; This is more consistent with the file marking feature than
  1732.   ;; dired-do-deletions.
  1733.   (interactive "P")
  1734.   (dired-internal-do-deletions
  1735.    ;; this may move point if ARG is an integer
  1736.    (dired-mark-map (cons (dired-get-filename) (point))
  1737.            arg)
  1738.    arg))
  1739.  
  1740. (defvar dired-deletion-confirmer 'yes-or-no-p) ; or y-or-n-p?
  1741.  
  1742. (defun dired-internal-do-deletions (l arg)
  1743.   ;; L is an alist of files to delete, with their buffer positions.
  1744.   ;; ARG is the prefix arg.
  1745.   ;; Filenames are absolute (VMS needs this for logical search paths).
  1746.   ;; (car L) *must* be the *last* (bottommost) file in the dired buffer.
  1747.   ;; That way as changes are made in the buffer they do not shift the
  1748.   ;; lines still to be changed, so the (point) values in L stay valid.
  1749.   ;; Also, for subdirs in natural order, a subdir's files are deleted
  1750.   ;; before the subdir itself - the other way around would not work.
  1751.   (let ((files (mapcar (function car) l))
  1752.     (count (length l))
  1753.     (succ 0))
  1754.     ;; canonicalize file list for pop up
  1755.     (setq files (nreverse (mapcar (function dired-make-relative) files)))
  1756.     (if (dired-mark-pop-up
  1757.      " *Deletions*" 'delete files dired-deletion-confirmer
  1758.      (format "Delete %s " (dired-mark-prompt arg files)))
  1759.     (save-excursion
  1760.       (let (failures);; files better be in reverse order for this loop!
  1761.         (while l
  1762.           (goto-char (cdr (car l)))
  1763.           (let (buffer-read-only)
  1764.         (condition-case err
  1765.             (let ((fn (car (car l))))
  1766.               ;; This test is equivalent to
  1767.               ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
  1768.               ;; but more efficient
  1769.               (if (eq t (car (file-attributes fn)))
  1770.               (remove-directory fn)
  1771.             (delete-file fn))
  1772.               ;; if we get here, removing worked
  1773.               (setq succ (1+ succ))
  1774.               (message "%s of %s deletions" succ count)
  1775.               (delete-region (progn (beginning-of-line) (point))
  1776.                      (progn (forward-line 1) (point)))
  1777.               (dired-clean-up-after-deletion fn))
  1778.           (error;; catch errors from failed deletions
  1779.            (dired-log "%s\n" err)
  1780.            (setq failures (cons (car (car l)) failures)))))
  1781.           (setq l (cdr l)))
  1782.         (if (not failures)
  1783.         (message "%d deletion%s done" count (dired-plural-s count))
  1784.           (dired-log-summary
  1785.            (message "%d of %d deletion%s failed: %s"
  1786.             (length failures) count
  1787.             (dired-plural-s count)
  1788.             (prin1-to-string failures))))))
  1789.       (message "(No deletions performed)")))
  1790.   (dired-move-to-filename))
  1791.  
  1792. ;; This is a separate function for the sake of dired-x.el.
  1793. (defun dired-clean-up-after-deletion (fn)
  1794.   ;; Clean up after a deleted file or directory FN.
  1795.   (save-excursion (and (dired-goto-subdir fn)
  1796.                (dired-kill-subdir))))
  1797.  
  1798.  
  1799. (defun dired-replace-in-string (regexp newtext string)
  1800.   ;; Replace REGEXP with NEWTEXT everywhere in STRING and return result.
  1801.   ;; NEWTEXT is taken literally---no \\DIGIT escapes will be recognized.
  1802.   (let ((result "") (start 0) mb me)
  1803.     (while (string-match regexp string start)
  1804.       (setq mb (match-beginning 0)
  1805.         me (match-end 0)
  1806.         result (concat result (substring string start mb) newtext)
  1807.         start me))
  1808.     (concat result (substring string start))))
  1809.  
  1810. (defun dired-next-dirline (arg &optional opoint)
  1811.   "Goto ARG'th next directory file line."
  1812.   (interactive "p")
  1813.   (dired-check-ls-l)
  1814.   (or opoint (setq opoint (point)))
  1815.   (if (if (> arg 0)
  1816.       (re-search-forward dired-re-dir nil t arg)
  1817.     (beginning-of-line)
  1818.     (re-search-backward dired-re-dir nil t (- arg)))
  1819.       (dired-move-to-filename)        ; user may type `i' or `f'
  1820.     (goto-char opoint)
  1821.     (error "No more subdirectories")))
  1822.  
  1823. (defun dired-prev-dirline (arg)
  1824.   "Goto ARG'th previous directory file line."
  1825.   (interactive "p")
  1826.   (dired-next-dirline (- arg)))
  1827.  
  1828. (defun dired-unflag-all-files (flag &optional arg)
  1829.   "Remove a specific or all flags from every file.
  1830. With an arg, queries for each marked file.
  1831. Type \\[help-command] at that time for help."
  1832.   (interactive "sRemove flag: (default: all flags) \nP")
  1833.   (let ((count 0)
  1834.     (re (if (zerop (length flag)) dired-re-mark
  1835.           (concat "^" (regexp-quote flag)))))
  1836.     (save-excursion
  1837.       (let (buffer-read-only case-fold-search query
  1838.                  (help-form "\
  1839. Type SPC or `y' to unflag one file, DEL or `n' to skip to next,
  1840. `!' to unflag all remaining files with no more questions."))
  1841.     (goto-char (point-min))
  1842.     (while (re-search-forward re nil t)
  1843.       (if (or (not arg)
  1844.           (dired-query 'query "Unflag file `%s' ? "
  1845.                    (dired-get-filename t)))
  1846.           (progn (delete-char -1) (insert " ") (setq count (1+ count))))
  1847.       (forward-line 1))))
  1848.     (message "%s" (format "Flags removed: %d %s" count flag) )))
  1849.  
  1850. ;; pop ups and user input for file marking
  1851.  
  1852. (defun dired-marker-regexp ()
  1853.   (concat "^" (regexp-quote (char-to-string dired-marker-char))))
  1854.  
  1855. (defun dired-plural-s (count)
  1856.   (if (= 1 count) "" "s"))
  1857.  
  1858. (defun dired-mark-prompt (arg files)
  1859.   ;; Return a string for use in a prompt, either the current file
  1860.   ;; name, or the marker and a count of marked files.
  1861.   (let ((count (length files)))
  1862.     (if (= count 1)
  1863.     (car files)
  1864.       ;; more than 1 file:
  1865.       (if (integerp arg)
  1866.       ;; abs(arg) = count
  1867.       ;; Perhaps this is nicer, but it also takes more screen space:
  1868.       ;;(format "[%s %d files]" (if (> arg 0) "next" "previous")
  1869.       ;;                        count)
  1870.       (format "[next %d files]" arg)
  1871.     (format "%c [%d files]" dired-marker-char count)))))
  1872.  
  1873. (defvar dired-query-alist
  1874.   '((?\y . y) (?\040 . y)        ; `y' or SPC means accept once
  1875.     (?n . n) (?\177 . n)        ; `n' or DEL skips once
  1876.     (?! . yes)                ; `!' accepts rest
  1877.     (?q. no) (?\e . no)            ; `q' or ESC skips rest
  1878.     ;; None of these keys quit - use C-g for that.
  1879.     ))
  1880.  
  1881. (defun dired-query (qs-var qs-prompt &rest qs-args)
  1882.   ;; Query user and return nil or t.
  1883.   ;; Store answer in symbol VAR (which must initially be bound to nil).
  1884.   ;; Format PROMPT with ARGS.
  1885.   ;; Binding variable help-form will help the user who types C-h.
  1886.   (let* ((char (symbol-value qs-var))
  1887.      (action (cdr (assoc char dired-query-alist))))
  1888.     (cond ((eq 'yes action)
  1889.        t)                ; accept, and don't ask again
  1890.       ((eq 'no action)
  1891.        nil)                ; skip, and don't ask again
  1892.       (t;; no lasting effects from last time we asked - ask now
  1893.        (let ((qprompt (concat qs-prompt
  1894.                   (if help-form
  1895.                       (format " [Type yn!q or %s] "
  1896.                           (key-description
  1897.                            (char-to-string help-char)))
  1898.                     " [Type y, n, q or !] ")))
  1899.          result elt)
  1900.          ;; Actually it looks nicer without cursor-in-echo-area - you can
  1901.          ;; look at the dired buffer instead of at the prompt to decide.
  1902.          (apply 'message qprompt qs-args)
  1903.          (setq char (set qs-var (read-char)))
  1904.          (while (not (setq elt (assoc char dired-query-alist)))
  1905.            (message "Invalid char - type %c for help." help-char)
  1906.            (ding)
  1907.            (sit-for 1)
  1908.            (apply 'message qprompt qs-args)
  1909.            (setq char (set qs-var (read-char))))
  1910.          (memq (cdr elt) '(t y yes)))))))
  1911.  
  1912. (defun dired-pop-to-buffer (buf)
  1913.   ;; Pop up buffer BUF.
  1914.   ;; If dired-shrink-to-fit is t, make its window fit its contents.
  1915.   (if (not dired-shrink-to-fit)
  1916.       (pop-to-buffer (get-buffer-create buf))
  1917.     ;; let window shrink to fit:
  1918.     (let ((window (selected-window))
  1919.       target-lines w2)
  1920.       (cond ;; if split-window-threshold is enabled, use the largest window
  1921.             ((and (> (window-height (setq w2 (get-largest-window)))
  1922.              split-height-threshold)
  1923.           (= (screen-width) (window-width w2)))
  1924.          (setq window w2))
  1925.         ;; if the least-recently-used window is big enough, use it
  1926.         ((and (> (window-height (setq w2 (get-lru-window)))
  1927.              (* 2 window-min-height))
  1928.           (= (screen-width) (window-width w2)))
  1929.          (setq window w2)))
  1930.       (save-excursion
  1931.     (set-buffer buf)
  1932.     (goto-char (point-max))
  1933.     (skip-chars-backward "\n\r\t ")
  1934.     (setq target-lines (count-lines (point-min) (point))))
  1935.       (if (<= (window-height window) (* 2 window-min-height))
  1936.       ;; At this point, every window on the screen is too small to split.
  1937.       (setq w2 (display-buffer buf))
  1938.     (setq w2 (split-window window
  1939.           (max window-min-height
  1940.                (- (window-height window)
  1941.               (1+ (max window-min-height target-lines)))))))
  1942.       (set-window-buffer w2 buf)
  1943.       (if (< (1- (window-height w2)) target-lines)
  1944.       (progn
  1945.         (select-window w2)
  1946.         (enlarge-window (- target-lines (1- (window-height w2))))))
  1947.       (set-window-start w2 1)
  1948.       )))
  1949.  
  1950. (defvar dired-no-confirm nil
  1951. ;;  "If non-nil, list of symbols for commands dired should not confirm.
  1952. ;;It can be a sublist of
  1953. ;;
  1954. ;;  '(byte-compile chgrp chmod chown compress copy delete hardlink load
  1955. ;;    move print shell symlink uncompress)"
  1956.   )
  1957.  
  1958. (defun dired-mark-confirm (op-symbol arg)
  1959.   ;; Request confirmation from the user that the operation described
  1960.   ;; by OP-SYMBOL is to be performed on the marked files.
  1961.   ;; Confirmation consists in a y-or-n question with a file list
  1962.   ;; pop-up unless OP-SYMBOL is a member of `dired-no-confirm'.
  1963.   ;; The files used are determined by ARG (like in dired-mark-get-files).
  1964.   (or (memq op-symbol dired-no-confirm)
  1965.       (let ((files (dired-mark-get-files t arg)))
  1966.     (dired-mark-pop-up nil op-symbol files (function y-or-n-p)
  1967.                (concat (capitalize (symbol-name op-symbol)) " "
  1968.                    (dired-mark-prompt arg files) "? ")))))
  1969.  
  1970. (defun dired-mark-pop-up (bufname op-symbol files function &rest args)
  1971.   ;;"Args BUFNAME OP-SYMBOL FILES FUNCTION &rest ARGS.
  1972.   ;;Return FUNCTION's result on ARGS after popping up a window (in a buffer
  1973.   ;;named BUFNAME, nil gives \" *Marked Files*\") showing the marked
  1974.   ;;files.  Uses function `dired-pop-to-buffer' to do that.
  1975.   ;; FUNCTION should not manipulate files.
  1976.   ;; It should only read input (an argument or confirmation).
  1977.   ;;The window is not shown if there is just one file or
  1978.   ;; OP-SYMBOL is a member of the list in `dired-no-confirm'.
  1979.   ;;FILES is the list of marked files."
  1980.   (or bufname (setq bufname  " *Marked Files*"))
  1981.   (if (or (memq op-symbol dired-no-confirm)
  1982.       (= (length files) 1))
  1983.       (apply function args)
  1984.     (save-excursion
  1985.       (set-buffer (get-buffer-create bufname))
  1986.       (erase-buffer)
  1987.       (dired-format-columns-of-files files))
  1988.     (save-window-excursion
  1989.       (dired-pop-to-buffer bufname)
  1990.       (apply function args))))
  1991.  
  1992. (defun dired-format-columns-of-files (files)
  1993.   ;; Files should be in forward order for this loop.
  1994.   ;; i.e., (car files) = first file in buffer.
  1995.   ;; Returns the number of lines used.
  1996.   (let* ((maxlen (+ 2 (apply 'max (mapcar 'length files))))
  1997.      (width (- (window-width (selected-window)) 2))
  1998.      (columns (max 1 (/ width maxlen)))
  1999.      (nfiles (length files))
  2000.      (rows (+ (/ nfiles columns)
  2001.           (if (zerop (% nfiles columns)) 0 1)))
  2002.      (i 0)
  2003.      (j 0))
  2004.     (setq files (nconc (copy-sequence files) ; fill up with empty fns
  2005.                (make-list (- (* columns rows) nfiles) "")))
  2006.     (setcdr (nthcdr (1- (length files)) files) files) ; make circular
  2007.     (while (< j rows)
  2008.       (while (< i columns)
  2009.     (indent-to (* i maxlen))
  2010.     (insert (car files))
  2011.     (setq files (nthcdr rows files)
  2012.           i (1+ i)))
  2013.       (insert "\n")
  2014.       (setq i 0
  2015.         j (1+ j)
  2016.         files (cdr files)))
  2017.     rows))
  2018.  
  2019. ;; Read arguments for a mark command of type OP-SYMBOL,
  2020. ;; perhaps popping up the list of marked files.
  2021. ;; ARG is the prefix arg and indicates whether the files came from
  2022. ;; marks (ARG=nil) or a repeat factor (integerp ARG).
  2023. ;; If the current file was used, the list has but one element and ARG
  2024. ;; does not matter. (It is non-nil, non-integer in that case, namely '(4)).
  2025.  
  2026. (defun dired-mark-read-string (prompt initial op-symbol arg files)
  2027.   ;; PROMPT for a string, with INITIAL input.
  2028.   ;; Other args are used to give user feedback and pop-up:
  2029.   ;; OP-SYMBOL of command, prefix ARG, marked FILES.
  2030.   (dired-mark-pop-up
  2031.    nil op-symbol files
  2032.    (function read-string)
  2033.    (format prompt (dired-mark-prompt arg files)) initial))
  2034.  
  2035. (defun dired-mark-read-file-name (prompt dir op-symbol arg files)
  2036.   (dired-mark-pop-up
  2037.    nil op-symbol files
  2038.    (function read-file-name)
  2039.    (format prompt (dired-mark-prompt arg files)) dir))
  2040.  
  2041. (defun dired-mark-file (arg)
  2042.   "In dired, mark the current line's file for later commands.
  2043. With arg, repeat over several lines.
  2044. Use \\[dired-unflag-all-files] to remove all flags."
  2045.   (interactive "p")
  2046.   (let (buffer-read-only)
  2047.     (dired-repeat-over-lines
  2048.      arg
  2049.      (function (lambda () (delete-char 1) (insert dired-marker-char))))))
  2050.  
  2051. (defun dired-next-marked-file (arg &optional wrap opoint)
  2052.   "Move to the next marked file, wrapping around the end of the buffer."
  2053.   (interactive "p\np")
  2054.   (or opoint (setq opoint (point)));; return to where interactively started
  2055.   (if (if (> arg 0)
  2056.       (re-search-forward dired-re-mark nil t arg)
  2057.     (beginning-of-line)
  2058.     (re-search-backward dired-re-mark nil t (- arg)))
  2059.       (dired-move-to-filename)
  2060.     (if (null wrap)
  2061.     (progn
  2062.       (goto-char opoint)
  2063.       (error "No next marked file"))
  2064.       (message "(Wraparound for next marked file)")
  2065.       (goto-char (if (> arg 0) (point-min) (point-max)))
  2066.       (dired-next-marked-file arg nil opoint))))
  2067.  
  2068. (defun dired-prev-marked-file (arg &optional wrap)
  2069.   "Move to the previous marked file, wrapping around the end of the buffer."
  2070.   (interactive "p\np")
  2071.   (dired-next-marked-file (- arg) wrap))
  2072.  
  2073. (defun dired-file-marker (file)
  2074.   ;; Return FILE's marker, or nil if unmarked.
  2075.   (save-excursion
  2076.     (and (dired-goto-file file)
  2077.      (progn
  2078.        (beginning-of-line)
  2079.        (if (not (equal ?\040 (following-char)))
  2080.            (following-char))))))
  2081.  
  2082. (defun dired-read-regexp (prompt &optional initial)
  2083. ;; This is an extra function so that gmhist can redefine it.
  2084.   (setq dired-flagging-regexp
  2085.     (read-string prompt (or initial dired-flagging-regexp))))
  2086.  
  2087. (defun dired-mark-files-regexp (regexp &optional marker-char)
  2088.   "Mark all files matching REGEXP for use in later commands.
  2089. A prefix argument means to unmark them instead.
  2090. `.' and `..' are never marked.
  2091.  
  2092. REGEXP is an Emacs regexp, not a shell wildcard.  Thus, use `\\.o$' for
  2093. object files--just `.o' will mark more than you might think."
  2094.   (interactive
  2095.    (list (dired-read-regexp (concat (if current-prefix-arg "Unmark" "Mark")
  2096.                     " files (regexp): "))
  2097.      (if current-prefix-arg ?\040)))
  2098.   (let ((dired-marker-char (or marker-char dired-marker-char)))
  2099.     (dired-mark-if
  2100.      (and (not (looking-at dired-re-dot))
  2101.       (not (eolp))            ; empty line
  2102.       (let ((fn (dired-get-filename nil t)))
  2103.         (and fn (string-match regexp (file-name-nondirectory fn)))))
  2104.      "matching file")))
  2105.  
  2106. (defun dired-flag-regexp-files (regexp)
  2107.   "In dired, flag all files containing the specified REGEXP for deletion.
  2108. The match is against the non-directory part of the filename.  Use `^'
  2109.   and `$' to anchor matches.  Exclude subdirs by hiding them.
  2110. `.' and `..' are never flagged."
  2111.   (interactive (list (dired-read-regexp "Flag for deletion (regexp): ")))
  2112.   (dired-mark-files-regexp regexp dired-del-marker))
  2113.  
  2114. (defun dired-mark-symlinks (unflag-p)
  2115.   "Mark all symbolic links.
  2116. With prefix argument, unflag all those files."
  2117.   (interactive "P")
  2118.   (dired-check-ls-l)
  2119.   (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
  2120.     (dired-mark-if (looking-at dired-re-sym) "symbolic link")))
  2121.  
  2122. (defun dired-mark-directories (unflag-p)
  2123.   "Mark all directory file lines except `.' and `..'.
  2124. With prefix argument, unflag all those files."
  2125.   (interactive "P")
  2126.   (dired-check-ls-l)
  2127.   (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
  2128.     (dired-mark-if (and (looking-at dired-re-dir)
  2129.             (not (looking-at dired-re-dot)))
  2130.            "directory file")))
  2131.  
  2132. (defun dired-mark-executables (unflag-p)
  2133.   "Mark all executable files.
  2134. With prefix argument, unflag all those files."
  2135.   (interactive "P")
  2136.   (dired-check-ls-l)
  2137.   (let ((dired-marker-char (if unflag-p ?\040 dired-marker-char)))
  2138.     (dired-mark-if (looking-at dired-re-exe) "executable file")))
  2139.  
  2140. ;; dired-x.el has a dired-mark-sexp interactive command: mark
  2141. ;; files for which PREDICATE returns non-nil.
  2142.  
  2143. (defun dired-flag-auto-save-files (&optional unflag-p)
  2144.   "Flag for deletion files whose names suggest they are auto save files.
  2145. A prefix argument says to unflag those files instead."
  2146.   (interactive "P")
  2147.   (dired-check-ls-l)
  2148.   (let ((dired-marker-char (if unflag-p ?\040 dired-del-marker)))
  2149.     (dired-mark-if
  2150.        (and (not (looking-at dired-re-dir))
  2151.         (let ((fn (dired-get-filename t t)))
  2152.           (if fn (auto-save-file-name-p
  2153.               (file-name-nondirectory fn)))))
  2154.        "auto save file")))
  2155.  
  2156. (defun dired-flag-backup-files (&optional unflag-p)
  2157.   "Flag all backup files (names ending with `~') for deletion.
  2158. With prefix argument, unflag these files."
  2159.   (interactive "P")
  2160.   (dired-check-ls-l)
  2161.   (let ((dired-marker-char (if unflag-p ?\040 dired-del-marker)))
  2162.     (dired-mark-if
  2163.      (and (not (looking-at dired-re-dir))
  2164.       (let ((fn (dired-get-filename t t)))
  2165.         (if fn (backup-file-name-p fn))))
  2166.      "backup file")))
  2167.  
  2168.  
  2169. ;;; Shell commands
  2170. ;;>>> install (move this function into simple.el)
  2171. (defun shell-quote (filename)        ; actually belongs into simple.el
  2172.   "Quote a file name for inferior shell (see variable shell-file-name)."
  2173.   ;; Quote everything except POSIX filename characters.
  2174.   ;; This should be safe enough even for really wierd shells.
  2175.   (let ((result "") (start 0) end)
  2176.     (while (string-match "[^---0-9a-zA-Z_./]" filename start)
  2177.       (setq end (match-beginning 0)
  2178.         result (concat result (substring filename start end)
  2179.                "\\" (substring filename end (1+ end)))
  2180.         start (1+ end)))
  2181.     (concat result (substring filename start))))
  2182.  
  2183. (defun dired-read-shell-command (prompt arg files)
  2184. ;;  "Read a dired shell command prompting with PROMPT (using read-string).
  2185. ;;ARG is the prefix arg and may be used to indicate in the prompt which
  2186. ;;  files are affected.
  2187. ;;This is an extra function so that you can redefine it, e.g., to use gmhist."
  2188.   (dired-mark-pop-up
  2189.    nil 'shell files
  2190.    (function read-string) (format prompt (dired-mark-prompt arg files))))
  2191.  
  2192. ;; The in-background argument is only needed in Emacs 18 where
  2193. ;; shell-command doesn't understand an appended ampersand `&'.
  2194. (defun dired-do-shell-command (&optional arg in-background)
  2195.   "Run a shell command on the marked files.
  2196. If there is output, it goes to a separate buffer.
  2197. The list of marked files is appended to the command string unless asterisks
  2198.   `*' indicate the place(s) where the list should go.
  2199. If no files are marked or a specific numeric prefix arg is given, uses
  2200.   next ARG files.  As always, a raw arg (\\[universal-argument]) means the current file.
  2201.   The prompt mentions the file(s) or the marker, as appropriate.
  2202. With a zero argument, run command on each marked file separately: `cmd *
  2203.   foo' results in `cmd F1 foo; ...; cmd Fn foo'.
  2204. No automatic redisplay is attempted, as the file names may have
  2205.   changed.  Type \\[dired-do-redisplay] to redisplay the marked files.
  2206. The shell command has the top level directory as working directory, so
  2207.   output files usually are created there instead of in a subdir."
  2208. ;;Functions dired-run-shell-command and dired-shell-stuff-it do the
  2209. ;;actual work and can be redefined for customization.
  2210.   (interactive "P")
  2211.   (let* ((on-each (equal arg 0))
  2212.      (prompt (concat (if in-background "& on " "! on ")
  2213.              (if on-each "each " "")
  2214.              "%s: "))
  2215.      (file-list (dired-mark-get-files t (if on-each nil arg)))
  2216.      ;; Want to give feedback whether this file or marked files are used:
  2217.      (command (dired-read-shell-command
  2218.            prompt (if on-each nil arg) file-list))
  2219.      (result
  2220.       (dired-shell-stuff-it command file-list on-each arg)))
  2221.     ;; execute the shell command
  2222.     (dired-run-shell-command result in-background)))
  2223.  
  2224. ;; Might use {,} for bash or csh:
  2225. (defvar dired-mark-prefix ""
  2226.   "Prepended to marked files in dired shell commands.")
  2227. (defvar dired-mark-postfix ""
  2228.   "Appended to marked files in dired shell commands.")
  2229. (defvar dired-mark-separator " "
  2230.   "Separates marked files in dired shell commands.")
  2231.  
  2232. (defun dired-shell-stuff-it (command file-list on-each &optional raw-arg)
  2233. ;; "Make up a shell command line from COMMAND and FILE-LIST.
  2234. ;; If ON-EACH is t, COMMAND should be applied to each file, else
  2235. ;; simply concat all files and apply COMMAND to this.
  2236. ;; FILE-LIST's elements will be quoted for the shell."
  2237. ;; Might be redefined for smarter things and could then use RAW-ARG
  2238. ;; (coming from interactive P and currently ignored) to decide what to do.
  2239. ;; Smart would be a way to access basename or extension of file names.
  2240. ;; See dired-trns.el for an approach to this.
  2241.   ;; Bug: There is no way to quote a *
  2242.   ;; On the other hand, you can never accidentally get a * into your cmd.
  2243.   (let ((stuff-it
  2244.      (if (string-match "\\*" command)
  2245.          (function (lambda (x)
  2246.              (dired-replace-in-string "\\*" x command)))
  2247.        (function (lambda (x) (concat command " " x))))))
  2248.     (if on-each
  2249.     (mapconcat stuff-it (mapcar (function shell-quote) file-list) ";")
  2250.       (let ((fns (mapconcat (function shell-quote)
  2251.                 file-list dired-mark-separator)))
  2252.     (if (> (length file-list) 1)
  2253.         (setq fns (concat dired-mark-prefix fns dired-mark-postfix)))
  2254.     (funcall stuff-it fns)))))
  2255.  
  2256. ;; This is an extra function so that it can be redefined by ange-ftp.
  2257. (defun dired-run-shell-command (command &optional in-background)
  2258.   (if (not in-background)
  2259.       (shell-command command)
  2260.     ;; We need this only in Emacs 18 (19's shell command has `&').
  2261.     ;; comint::background is defined in emacs-19.el.
  2262.     (comint::background command)))
  2263.  
  2264. (defun dired-do-print (&optional arg)
  2265.   "Print the marked (or next ARG) files.
  2266. Uses the shell command coming from variables `lpr-command' and
  2267. `lpr-switches' as default."
  2268.   (interactive "P")
  2269.   (or (listp lpr-switches)
  2270.       (error "lpr-switches must be a *list* of strings"))
  2271.   (let* ((file-list (dired-mark-get-files t arg))
  2272.      (switches (mapconcat (function identity) lpr-switches " "))
  2273.      (command (dired-mark-read-string
  2274.            "Print %s with: "
  2275.            (concat lpr-command " " switches)
  2276.            'print arg file-list)))
  2277.     (dired-run-shell-command (dired-shell-stuff-it command file-list nil))))
  2278.  
  2279.  
  2280. ;;; 10K
  2281. ;;;###begin dired-cp.el
  2282. ;;; Copy, move/rename, making hard and symbolic links
  2283.  
  2284. (defvar dired-backup-if-overwrite nil
  2285.   "*Non-nil if Dired should ask about making backups before overwriting files.
  2286. Special value 'always suppresses confirmation.")
  2287.  
  2288. (defun dired-handle-overwrite (to)
  2289.   ;; Save old version of a to be overwritten file TO.
  2290.   ;; `overwrite-confirmed' and `overwrite-backup-query' are fluid vars
  2291.   ;; from dired-create-files.
  2292.   (if (and dired-backup-if-overwrite
  2293.        overwrite-confirmed
  2294.        (or (eq 'always dired-backup-if-overwrite)
  2295.            (dired-query 'overwrite-backup-query
  2296.             (format "Make backup for existing file `%s'? " to))))
  2297.       (let ((backup (car (find-backup-file-name to))))
  2298.     (rename-file to backup 0)    ; confirm overwrite of old backup
  2299.     (dired-relist-entry backup))))
  2300.  
  2301. (defun dired-copy-file (from to ok-flag)
  2302.   (dired-handle-overwrite to)
  2303.   (copy-file from to ok-flag dired-copy-preserve-time))
  2304.  
  2305. (defun dired-rename-file (from to ok-flag)
  2306.   (dired-handle-overwrite to)
  2307.   (rename-file from to ok-flag)        ; error is caught in -create-files
  2308.   ;; Silently rename the visited file of any buffer visiting this file.
  2309.   (and (get-file-buffer from)
  2310.        (save-excursion
  2311.      (set-buffer (get-file-buffer from))
  2312.      (let ((modflag (buffer-modified-p)))
  2313.        (set-visited-file-name to)    ; kills write-file-hooks
  2314.        (set-buffer-modified-p modflag))))
  2315.   (dired-remove-file from)
  2316.   ;; See if it's an inserted subdir, and rename that, too.
  2317.   (dired-rename-subdir from to))
  2318.  
  2319. (defun dired-rename-subdir (from-dir to-dir)
  2320.   (setq from-dir (file-name-as-directory from-dir)
  2321.     to-dir (file-name-as-directory to-dir))
  2322.   (dired-fun-in-all-buffers from-dir
  2323.                 (function dired-rename-subdir-1) from-dir to-dir)
  2324.   ;; Update visited file name of all affected buffers
  2325.   (let ((blist (buffer-list)))
  2326.     (while blist
  2327.       (save-excursion
  2328.         (set-buffer (car blist))
  2329.     (if (and buffer-file-name
  2330.          (dired-in-this-tree buffer-file-name from-dir))
  2331.         (let ((modflag (buffer-modified-p))
  2332.           (to-file (dired-replace-in-string
  2333.                 (concat "^" (regexp-quote from-dir))
  2334.                 to-dir
  2335.                 buffer-file-name)))
  2336.           (set-visited-file-name to-file)
  2337.           (set-buffer-modified-p modflag))))
  2338.       (setq blist (cdr blist)))))
  2339.  
  2340. (defun dired-rename-subdir-1 (dir to)
  2341.   ;; Rename DIR to TO in headerlines and dired-subdir-alist, if DIR or
  2342.   ;; one of its subdirectories is expanded in this buffer.
  2343.   (let ((alist dired-subdir-alist)
  2344.     (elt nil))
  2345.     (while alist
  2346.       (setq elt (car alist)
  2347.         alist (cdr alist))
  2348.       (if (dired-in-this-tree (car elt) dir)
  2349.       ;; ELT's subdir is affected by the rename
  2350.       (dired-rename-subdir-2 elt dir to)))
  2351.     (if (equal dir default-directory)
  2352.     ;; if top level directory was renamed, lots of things have to be
  2353.     ;; updated:
  2354.     (progn
  2355.       (dired-unadvertise dir)    ; we no longer dired DIR...
  2356.       (setq default-directory to
  2357.         dired-directory (expand-file-name;; this is correct
  2358.                  ;; with and without wildcards
  2359.                  (file-name-nondirectory dired-directory)
  2360.                  to))
  2361.       (let ((new-name (file-name-nondirectory
  2362.                (directory-file-name dired-directory))))
  2363.         ;; try to rename buffer, but just leave old name if new
  2364.         ;; name would already exist (don't try appending "<%d>")
  2365.         (or (get-buffer new-name)
  2366.         (rename-buffer new-name)))
  2367.       ;; ... we dired TO now:
  2368.       (dired-advertise)))))
  2369.  
  2370. (defun dired-rename-subdir-2 (elt dir to)
  2371.   ;; Update the headerline and dired-subdir-alist element of directory
  2372.   ;; described by alist-element ELT to reflect the moving of DIR to TO.
  2373.   ;; Thus, ELT describes either DIR itself or a subdir of DIR.
  2374.  
  2375.   ;; Bug: If TO is not longer part of the same dired tree as DIR was,
  2376.   ;; updating the headerline is actually not the right thing---it
  2377.   ;; should be removed in that case and a completely new entry be
  2378.   ;; added for TO.  Actually, removing and adding anew would always be
  2379.   ;; the right (but slow) way of doing it.
  2380.  
  2381.   ;; The consequences are pretty harmless though (no updates since
  2382.   ;; dired-buffers-for-dir will not suspect it to be in this dired
  2383.   ;; buffer).
  2384.  
  2385.   (save-excursion
  2386.     (let ((regexp (regexp-quote (directory-file-name dir)))
  2387.       (newtext (directory-file-name to))
  2388.       buffer-read-only)
  2389.       (goto-char (dired-get-subdir-min elt))
  2390.       ;; Update subdir headerline in buffer
  2391.       (if (not (looking-at dired-subdir-regexp))
  2392.       (error "%s not found where expected - dired-subdir-alist broken?"
  2393.          dir)
  2394.     (goto-char (match-beginning 1))
  2395.     (if (re-search-forward regexp (match-end 1) t)
  2396.         (replace-match newtext t t)
  2397.       (error "Expected to find `%s' in headerline of %s" dir (car elt))))
  2398.       ;; Update buffer-local dired-subdir-alist
  2399.       (setcar elt
  2400.           (dired-normalize-subdir
  2401.            (dired-replace-in-string regexp newtext (car elt)))))))
  2402.  
  2403. ;; Cloning replace-match to work on strings instead of in buffer:
  2404. ;; The FIXEDCASE parameter of replace-match is not implemented.
  2405. (defun dired-string-replace-match (regexp string newtext
  2406.                       &optional literal global)
  2407.   "Replace first match of REGEXP in STRING with NEWTEXT.
  2408. If it does not match, nil is returned instead of the new string.
  2409. Optional arg LITERAL means to take NEWTEXT literally.
  2410. Optional arg GLOBAL means to replace all matches."
  2411.   (if global
  2412.         (let ((result "") (start 0) mb me)
  2413.       (while (string-match regexp string start)
  2414.         (setq mb (match-beginning 0)
  2415.           me (match-end 0)
  2416.           result (concat result
  2417.                  (substring string start mb)
  2418.                  (if literal
  2419.                      newtext
  2420.                    (dired-expand-newtext string newtext)))
  2421.           start me))
  2422.       (if mb            ; matched at least once
  2423.           (concat result (substring string start))
  2424.         nil))
  2425.     ;; not GLOBAL
  2426.     (if (not (string-match regexp string 0))
  2427.     nil
  2428.       (concat (substring string 0 (match-beginning 0))
  2429.           (if literal newtext (dired-expand-newtext string newtext))
  2430.           (substring string (match-end 0))))))
  2431.  
  2432. (defun dired-expand-newtext (string newtext)
  2433.   ;; Expand \& and \1..\9 (referring to STRING) in NEWTEXT, using match data.
  2434.   ;; Note that in Emacs 18 match data are clipped to current buffer
  2435.   ;; size...so the buffer should better not be smaller than STRING.
  2436.   (let ((pos 0)
  2437.     (len (length newtext))
  2438.     (expanded-newtext ""))
  2439.     (while (< pos len)
  2440.       (setq expanded-newtext
  2441.         (concat expanded-newtext
  2442.             (let ((c (aref newtext pos)))
  2443.               (if (= ?\\ c)
  2444.               (cond ((= ?\& (setq c
  2445.                           (aref newtext
  2446.                             (setq pos (1+ pos)))))
  2447.                  (substring string
  2448.                         (match-beginning 0)
  2449.                         (match-end 0)))
  2450.                 ((and (>= c ?1) (<= c ?9))
  2451.                  ;; return empty string if N'th
  2452.                  ;; sub-regexp did not match:
  2453.                  (let ((n (- c ?0)))
  2454.                    (if (match-beginning n)
  2455.                        (substring string
  2456.                           (match-beginning n)
  2457.                           (match-end n))
  2458.                      "")))
  2459.                 (t
  2460.                  (char-to-string c)))
  2461.             (char-to-string c)))))
  2462.       (setq pos (1+ pos)))
  2463.     expanded-newtext))
  2464.  
  2465. ;; The basic function for half a dozen variations on cp/mv/ln/ln -s.
  2466. (defun dired-create-files (file-creator operation fn-list name-constructor
  2467.                     &optional marker-char)
  2468.  
  2469. ;; Create a new file for each from a list of existing files.  The user
  2470. ;; is queried, dired buffers are updated, and at the end a success or
  2471. ;; failure message is displayed
  2472.  
  2473. ;; FILE-CREATOR must accept three args: oldfile newfile ok-if-already-exists
  2474.  
  2475. ;; It is called for each file and must create newfile, the entry of
  2476. ;; which will be added.  The user will be queried if the file already
  2477. ;; exists.  If oldfile is removed by FILE-CREATOR (i.e, it is a
  2478. ;; rename), it is FILE-CREATOR's responsibility to update dired
  2479. ;; buffers.  FILE-CREATOR must abort by signalling a file-error if it
  2480. ;; could not create newfile.  The error is caught and logged.
  2481.  
  2482. ;; OPERATION (a capitalized string, e.g. `Copy') describes the
  2483. ;; operation performed.  It is used for error logging.
  2484.  
  2485. ;; FN-LIST is the list of files to copy (full absolute pathnames).
  2486.  
  2487. ;; NAME-CONSTRUCTOR returns a newfile for every oldfile, or nil to
  2488. ;; skip.  If it skips files for other reasons than a direct user
  2489. ;; query, it is supposed to tell why (using dired-log).
  2490.  
  2491. ;; Optional MARKER-CHAR is a character with which to mark every
  2492. ;; newfile's entry, or t to use the current marker character if the
  2493. ;; oldfile was marked.
  2494.  
  2495.   (let (failures skipped (success-count 0) (total (length fn-list)))
  2496.     (let (to overwrite-query
  2497.          overwrite-backup-query)    ; for dired-handle-overwrite
  2498.       (mapcar
  2499.        (function
  2500.     (lambda (from)
  2501.       (setq to (funcall name-constructor from))
  2502.       (if (equal to from)
  2503.           (progn
  2504.         (setq to nil)
  2505.         (dired-log "Cannot %s to same file: %s\n"
  2506.                (downcase operation) from)))
  2507.       (if (not to)
  2508.           (setq skipped (cons (dired-make-relative from) skipped))
  2509.         (let* ((overwrite (file-exists-p to))
  2510.            (overwrite-confirmed    ; for dired-handle-overwrite
  2511.             (and overwrite
  2512.              (let ((help-form '(format "\
  2513. Type SPC or `y' to overwrite file `%s',
  2514. DEL or `n' to skip to next,
  2515. ESC or `q' to not overwrite any of the remaining files,
  2516. `!' to overwrite all remaining files with no more questions." to)))
  2517.                (dired-query 'overwrite-query
  2518.                     "Overwrite `%s'?" to))))
  2519.            ;; must determine if FROM is marked before file-creator
  2520.            ;; gets a chance to delete it (in case of a move).
  2521.            (actual-marker-char
  2522.             (cond  ((integerp marker-char) marker-char)
  2523.                (marker-char (dired-file-marker from)) ; slow
  2524.                (t nil))))
  2525.           (condition-case err
  2526.           (progn
  2527.             (funcall file-creator from to overwrite-confirmed)
  2528.             (if overwrite
  2529.             ;; If we get here, file-creator hasn't been aborted
  2530.             ;; and the old entry (if any) has to be deleted
  2531.             ;; before adding the new entry.
  2532.             (dired-remove-file to))
  2533.             (setq success-count (1+ success-count))
  2534.             (message "%s: %d of %d" operation success-count total)
  2535.             (dired-add-file to actual-marker-char))
  2536.         (file-error        ; FILE-CREATOR aborted
  2537.          (progn
  2538.            (setq failures (cons (dired-make-relative from) failures))
  2539.            (dired-log "%s `%s' to `%s' failed:\n%s\n"
  2540.                   operation from to err))))))))
  2541.        fn-list))
  2542.     (cond
  2543.      (failures
  2544.       (dired-log-summary
  2545.        (message "%s failed for %d of %d file%s %s"
  2546.         operation (length failures) total
  2547.         (dired-plural-s total) failures)))
  2548.      (skipped
  2549.       (dired-log-summary
  2550.        (message "%s: %d of %d file%s skipped %s"
  2551.         operation (length skipped) total
  2552.         (dired-plural-s total) skipped)))
  2553.      (t
  2554.       (message "%s: %s file%s."
  2555.            operation success-count (dired-plural-s success-count)))))
  2556.   (dired-move-to-filename))
  2557.  
  2558. (defun dired-do-create-files (op-symbol file-creator operation arg
  2559.                          &optional marker-char op1
  2560.                          how-to)
  2561.   ;; Create a new file for each marked file.
  2562.   ;; Prompts user for target, which is a directory in which to create
  2563.   ;;   the new files.  Target may be a plain file if only one marked
  2564.   ;;   file exists.
  2565.   ;; OP-SYMBOL is the symbol for the operation.  Function `dired-mark-pop-up'
  2566.   ;;   will determine wether pop-ups are appropriate for this OP-SYMBOL.
  2567.   ;; FILE-CREATOR and OPERATION as in dired-create-files.
  2568.   ;; ARG as in dired-mark-get-files.
  2569.   ;; Optional arg OP1 is an alternate form for OPERATION if there is
  2570.   ;;   only one file.
  2571.   ;; Optional arg MARKER-CHAR as in dired-create-files.
  2572.   ;; Optional arg HOW-TO determines how to treat target:
  2573.   ;;   If HOW-TO is not given (or nil), and target is a directory, the
  2574.   ;;     file(s) are created inside the target directory.  If target
  2575.   ;;     is not a directory, there must be exactly one marked file,
  2576.   ;;     else error.
  2577.   ;;   If HOW-TO is t, then target is not modified.  There must be
  2578.   ;;     exactly one marked file, else error.
  2579.   ;; Else HOW-TO is assumed to be a function of one argument, target,
  2580.   ;;     that looks at target and returns a value for the into-dir
  2581.   ;;     variable.  The function dired-into-dir-with-symlinks is provided
  2582.   ;;     for the case (common when creating symlinks) that symbolic
  2583.   ;;     links to directories are not to be considered as directories
  2584.   ;;     (as file-directory-p would if HOW-TO had been nil).
  2585.   (or op1 (setq op1 operation))
  2586.   (let* ((fn-list (dired-mark-get-files nil arg))
  2587.      (fn-count (length fn-list))
  2588.      (target (expand-file-name
  2589.            (dired-mark-read-file-name
  2590.             (concat (if (= 1 fn-count) op1 operation) " %s to: ")
  2591.             (dired-dwim-target-directory)
  2592.             op-symbol arg (mapcar (function dired-make-relative) fn-list))))
  2593.      (into-dir (cond ((null how-to) (file-directory-p target))
  2594.              ((eq how-to t) nil)
  2595.              (t (funcall how-to target)))))
  2596.     (if (and (> fn-count 1)
  2597.          (not into-dir))
  2598.     (error "Marked %s: target must be a directory: %s" operation target))
  2599.     ;; rename-file bombs when moving directories unless we do this:
  2600.     (or into-dir (setq target (directory-file-name target)))
  2601.     (dired-create-files
  2602.      file-creator operation fn-list
  2603.      (if into-dir            ; target is a directory
  2604.      ;; This function uses fluid vars into-dir and target when called
  2605.      ;; inside dired-create-files:
  2606.      (function (lambda (from)
  2607.              (expand-file-name (file-name-nondirectory from) target)))
  2608.        (function (lambda (from) target)))
  2609.      marker-char)))
  2610.  
  2611. (defun dired-dwim-target-directory ()
  2612.   ;; Try to guess which target directory the user may want.
  2613.   ;; If there is a dired buffer displayed in the next window, use
  2614.   ;; its current subdir, else use current subdir of this dired buffer.
  2615.   (let ((this-dir (and (eq major-mode 'dired-mode)
  2616.                (dired-current-directory))))
  2617.     ;; non-dired buffer may want to profit from this function, e.g. vm-uudecode
  2618.     (if dired-dwim-target
  2619.     (let* ((other-buf (window-buffer (next-window)))
  2620.            (other-dir (save-excursion
  2621.                 (set-buffer other-buf)
  2622.                 (and (eq major-mode 'dired-mode)
  2623.                  (dired-current-directory)))))
  2624.       (or other-dir this-dir))
  2625.       this-dir)))
  2626.  
  2627. (defun dired-into-dir-with-symlinks (target)
  2628.   (and (file-directory-p target)
  2629.        (not (file-symlink-p target))))
  2630. ;; This may not always be what you want, especially if target is your
  2631. ;; home directory and it happens to be a symbolic link, as is often the
  2632. ;; case with NFS and automounters.  Or if you want to make symlinks
  2633. ;; into directories that themselves are only symlinks, also quite
  2634. ;; common.
  2635.  
  2636. ;; So we don't use this function as value for HOW-TO in
  2637. ;; dired-do-symlink, which has the minor disadvantage of
  2638. ;; making links *into* a symlinked-dir, when you really wanted to
  2639. ;; *overwrite* that symlink.  In that (rare, I guess) case, you'll
  2640. ;; just have to remove that symlink by hand before making your marked
  2641. ;; symlinks.
  2642.  
  2643. (defun dired-do-copy (&optional arg)
  2644.   "Copy all marked (or next ARG) files, or copy the current file.
  2645. Thus, a zero prefix argument copies nothing.  But it toggles the
  2646. variable `dired-copy-preserve-time' (which see)."
  2647.   (interactive "P")
  2648.   (if (not (zerop (prefix-numeric-value arg)))
  2649.       (dired-do-create-files 'copy (function dired-copy-file)
  2650.                    (if dired-copy-preserve-time "Copy [-p]" "Copy")
  2651.                    arg dired-keep-marker-copy)
  2652.     (setq dired-copy-preserve-time (not dired-copy-preserve-time))
  2653.     (if dired-copy-preserve-time
  2654.     (message "Copy will preserve time.")
  2655.       (message "Copied files will get current date."))))
  2656.  
  2657. (defun dired-do-symlink (&optional arg)
  2658.    "Symlink all marked (or next ARG) files into a directory,
  2659. or make a symbolic link to the current file."
  2660.   (interactive "P")
  2661.   (dired-do-create-files 'symlink (function make-symbolic-link)
  2662.                "SymLink" arg dired-keep-marker-symlink))
  2663.  
  2664. (defun dired-do-hardlink (&optional arg)
  2665.    "Hard-link all marked (or next ARG) files into a directory,
  2666. or make a hard link to the current file."
  2667.   (interactive "P")
  2668.   (dired-do-create-files 'hardlink (function add-name-to-file)
  2669.                "HardLink" arg dired-keep-marker-hardlink))
  2670.  
  2671. (defun dired-do-move (&optional arg)
  2672.   "Move all marked (or next ARG) files into a directory,
  2673. or rename the current file.
  2674. A zero ARG moves no files but toggles `dired-dwim-target' (which see)."
  2675.   (interactive "P")
  2676.   (if (not (zerop (prefix-numeric-value arg)))
  2677.       (dired-do-create-files 'move (function dired-rename-file)
  2678.                    "Move" arg dired-keep-marker-move "Rename")
  2679.     (setq dired-dwim-target (not dired-dwim-target))
  2680.     (message "dired-dwim-target is %s." (if dired-dwim-target "ON" "OFF"))))
  2681.  
  2682. ;;;###end dired-cp.el
  2683.  
  2684. ;;; 5K
  2685. ;;;###begin dired-re.el
  2686. (defun dired-do-create-files-regexp
  2687.   (file-creator operation arg regexp newname &optional whole-path marker-char)
  2688.   ;; Create a new file for each marked file using regexps.
  2689.   ;; FILE-CREATOR and OPERATION as in dired-create-files.
  2690.   ;; ARG as in dired-mark-get-files.
  2691.   ;; Matches each marked file against REGEXP and constructs the new
  2692.   ;;   filename from NEWNAME (like in function replace-match).
  2693.   ;; Optional arg WHOLE-PATH means match/replace the whole pathname
  2694.   ;;   instead of only the non-directory part of the file.
  2695.   ;; Optional arg MARKER-CHAR as in dired-create-files.
  2696.   (let* ((fn-list (dired-mark-get-files nil arg))
  2697.      (fn-count (length fn-list))
  2698.      (operation-prompt (concat operation " `%s' to `%s'?"))
  2699.      (rename-regexp-help-form (format "\
  2700. Type SPC or `y' to %s one match, DEL or `n' to skip to next,
  2701. `!' to %s all remaining matches with no more questions."
  2702.                       (downcase operation)
  2703.                       (downcase operation)))
  2704.      (regexp-name-constructor
  2705.       ;; Function to construct new filename using REGEXP and NEWNAME:
  2706.       (if whole-path        ; easy (but rare) case
  2707.           (function
  2708.            (lambda (from)
  2709.          (let ((to (dired-string-replace-match regexp from newname))
  2710.                ;; must bind help-form directly around call to
  2711.                ;; dired-query
  2712.                (help-form rename-regexp-help-form))
  2713.            (if to
  2714.                (and (dired-query 'rename-regexp-query
  2715.                      operation-prompt
  2716.                      from
  2717.                      to)
  2718.                 to)
  2719.              (dired-log "%s: %s did not match regexp %s\n"
  2720.                 operation from regexp)))))
  2721.         ;; not whole-path, replace non-directory part only
  2722.         (function
  2723.          (lambda (from)
  2724.            (let* ((new (dired-string-replace-match
  2725.                 regexp (file-name-nondirectory from) newname))
  2726.               (to (and new    ; nil means there was no match
  2727.                    (expand-file-name new
  2728.                          (file-name-directory from))))
  2729.               (help-form rename-regexp-help-form))
  2730.          (if to
  2731.              (and (dired-query 'rename-regexp-query
  2732.                        operation-prompt
  2733.                        (dired-make-relative from)
  2734.                        (dired-make-relative to))
  2735.               to)
  2736.            (dired-log "%s: %s did not match regexp %s\n"
  2737.                   operation (file-name-nondirectory from) regexp)))))))
  2738.      rename-regexp-query)
  2739.     (dired-create-files
  2740.      file-creator operation fn-list regexp-name-constructor marker-char)))
  2741.  
  2742. (defun dired-mark-read-regexp (operation)
  2743.   ;; Prompt user about performing OPERATION.
  2744.   ;; Read and return list of: regexp newname arg whole-path.
  2745.   (let* ((whole-path
  2746.       (equal 0 (prefix-numeric-value current-prefix-arg)))
  2747.      (arg
  2748.       (if whole-path nil current-prefix-arg))
  2749.      (regexp
  2750.       (dired-read-regexp
  2751.        (concat (if whole-path "Path " "") operation " from (regexp): ")
  2752.        dired-flagging-regexp))
  2753.      (newname
  2754.       (read-string
  2755.        (concat (if whole-path "Path " "") operation " " regexp " to: "))))
  2756.     (list regexp newname arg whole-path)))
  2757.  
  2758. (defun dired-do-rename-regexp (regexp newname &optional arg whole-path)
  2759.   "Rename marked files containing REGEXP to NEWNAME.
  2760. As each match is found, the user must type a character saying
  2761.   what to do with it.  For directions, type \\[help-command] at that time.
  2762. NEWNAME may contain \\=\\<n> or \\& as in `query-replace-regexp'.
  2763. REGEXP defaults to the last regexp used.
  2764. With a zero prefix arg, renaming by regexp affects the complete
  2765.   pathname - usually only the non-directory part of file names is used
  2766.   and changed."
  2767.   (interactive (dired-mark-read-regexp "Rename"))
  2768.   (dired-do-create-files-regexp
  2769.    (function dired-rename-file)
  2770.    "Rename" arg regexp newname whole-path dired-keep-marker-move))
  2771.  
  2772. (defun dired-do-copy-regexp (regexp newname &optional arg whole-path)
  2773.   "Copy all marked files containing REGEXP to NEWNAME.
  2774. See function `dired-rename-regexp' for more info."
  2775.   (interactive (dired-mark-read-regexp "Copy"))
  2776.   (dired-do-create-files-regexp
  2777.    (function dired-copy-file)
  2778.    (if dired-copy-preserve-time "Copy [-p]" "Copy")
  2779.    arg regexp newname whole-path dired-keep-marker-copy))
  2780.  
  2781. (defun dired-do-hardlink-regexp (regexp newname &optional arg whole-path)
  2782.   "Hardlink all marked files containing REGEXP to NEWNAME.
  2783. See function `dired-rename-regexp' for more info."
  2784.   (interactive (dired-mark-read-regexp "HardLink"))
  2785.   (dired-do-create-files-regexp
  2786.    (function add-name-to-file)
  2787.    "HardLink" arg regexp newname whole-path dired-keep-marker-hardlink))
  2788.  
  2789. (defun dired-do-symlink-regexp (regexp newname &optional arg whole-path)
  2790.   "Symlink all marked files containing REGEXP to NEWNAME.
  2791. See function `dired-rename-regexp' for more info."
  2792.   (interactive (dired-mark-read-regexp "SymLink"))
  2793.   (dired-do-create-files-regexp
  2794.    (function make-symbolic-link)
  2795.    "SymLink" arg regexp newname whole-path dired-keep-marker-symlink))
  2796.  
  2797. (defun dired-create-files-non-directory
  2798.   (file-creator basename-constructor operation arg)
  2799.   ;; Perform FILE-CREATOR on the non-directory part of marked files
  2800.   ;; using function BASENAME-CONSTRUCTOR, with query for each file.
  2801.   ;; OPERATION like in dired-create-files, ARG like in dired-mark-get-files.
  2802.   (let (rename-non-directory-query)
  2803.     (dired-create-files
  2804.      file-creator
  2805.      operation
  2806.      (dired-mark-get-files nil arg)
  2807.      (function
  2808.       (lambda (from)
  2809.     (let ((to (concat (file-name-directory from)
  2810.               (funcall basename-constructor
  2811.                    (file-name-nondirectory from)))))
  2812.       (and (let ((help-form (format "\
  2813. Type SPC or `y' to %s one file, DEL or `n' to skip to next,
  2814. `!' to %s all remaining matches with no more questions."
  2815.                     (downcase operation)
  2816.                     (downcase operation))))
  2817.          (dired-query 'rename-non-directory-query
  2818.                   (concat operation " `%s' to `%s'")
  2819.                   (dired-make-relative from)
  2820.                   (dired-make-relative to)))
  2821.            to))))
  2822.      dired-keep-marker-move)))
  2823.  
  2824. (defun dired-rename-non-directory (basename-constructor operation arg)
  2825.   (dired-create-files-non-directory
  2826.    (function dired-rename-file)
  2827.    basename-constructor operation arg))
  2828.  
  2829. (defun dired-upcase (&optional arg)
  2830.   "Rename all marked (or next ARG) files to upper case."
  2831.   (interactive "P")
  2832.   (dired-rename-non-directory (function upcase) "Rename upcase" arg))
  2833.  
  2834. (defun dired-downcase (&optional arg)
  2835.   "Rename all marked (or next ARG) files to lower case."
  2836.   (interactive "P")
  2837.   (dired-rename-non-directory (function downcase) "Rename downcase" arg))
  2838.  
  2839. ;;;###end dired-re.el
  2840.  
  2841.  
  2842. ;; Tree Dired
  2843.  
  2844. ;;; utility functions
  2845.  
  2846. (defun dired-in-this-tree (file dir)
  2847.   ;;"Is FILE part of the directory tree starting at DIR?"
  2848.   (let (case-fold-search)
  2849.     (string-match (concat "^" (regexp-quote dir)) file)))
  2850.  
  2851. (defun dired-make-absolute (file &optional dir)
  2852.   ;;"Convert FILE (a pathname relative to DIR) to an absolute pathname."
  2853.   ;; We can't always use expand-file-name as this would get rid of `.'
  2854.   ;; or expand in / instead default-directory if DIR=="".
  2855.   ;; This should be good enough for ange-ftp, but might easily be
  2856.   ;; redefined (for VMS?).
  2857.   ;; It should be reasonably fast, though, as it is called in
  2858.   ;; dired-get-filename.
  2859.   (concat (or dir default-directory) file))
  2860.  
  2861. (defun dired-make-relative (file &optional dir no-error)
  2862.   ;;"Convert FILE (an absolute pathname) to a pathname relative to DIR.
  2863.   ;; Else error (unless NO-ERROR is non-nil, then FILE is returned unchanged)
  2864.   ;;DIR defaults to default-directory."
  2865.   ;; DIR must be file-name-as-directory, as with all directory args in
  2866.   ;; elisp code.
  2867.   (or dir (setq dir default-directory))
  2868.   (if (string-match (concat "^" (regexp-quote dir)) file)
  2869.       (substring file (match-end 0))
  2870.     (if no-error
  2871.     file
  2872.       (error  "%s: not in directory tree growing at %s" file dir))))
  2873.  
  2874. (defun dired-normalize-subdir (dir)
  2875.   ;; Prepend default-directory to DIR if relative path name.
  2876.   ;; dired-get-filename must be able to make a valid filename from a
  2877.   ;; file and its directory DIR.
  2878.   (file-name-as-directory
  2879.    (if (file-name-absolute-p dir)
  2880.        dir
  2881.      (expand-file-name dir default-directory))))
  2882.  
  2883. (defun dired-between-files ()
  2884.   ;; Point must be at beginning of line
  2885.   ;; Should be equivalent to (save-excursion (not (dired-move-to-filename)))
  2886.   ;; but is about 1.5..2.0 times as fast. (Actually that's not worth it)
  2887.   (or (looking-at "^$\\|^. *$\\|^. total\\|^. wildcard")
  2888.       (looking-at dired-subdir-regexp)))
  2889.  
  2890. (defun dired-get-subdir ()
  2891.   ;;"Return the subdir name on this line, or nil if not on a headerline."
  2892.   ;; Look up in the alist whether this is a headerline.
  2893.   (save-excursion
  2894.     (let ((cur-dir (dired-current-directory)))
  2895.       (beginning-of-line)        ; alist stores b-o-l positions
  2896.       (and (zerop (- (point)
  2897.              (dired-get-subdir-min (assoc cur-dir
  2898.                           dired-subdir-alist))))
  2899.        cur-dir))))
  2900.  
  2901. ;(defun dired-get-subdir-min (elt)
  2902. ;  (cdr elt))
  2903. ;; can't use macro,  must be redefinable for other alist format in dired-nstd.
  2904. (fset 'dired-get-subdir-min 'cdr)
  2905.  
  2906. (defun dired-get-subdir-max (elt)
  2907.   (save-excursion
  2908.     (goto-char (dired-get-subdir-min elt))
  2909.     (dired-subdir-max)))
  2910.  
  2911. (defun dired-clear-alist ()
  2912.   (while dired-subdir-alist
  2913.     (set-marker (dired-get-subdir-min (car dired-subdir-alist)) nil)
  2914.     (setq dired-subdir-alist (cdr dired-subdir-alist))))
  2915.  
  2916. (defun dired-simple-subdir-alist ()
  2917.   ;; Build and return `dired-subdir-alist' assuming just the top level
  2918.   ;; directory to be inserted.  Don't parse the buffer.
  2919.   (set (make-local-variable 'dired-subdir-alist)
  2920.        (list (cons default-directory (point-min-marker)))))
  2921.  
  2922. (defun dired-build-subdir-alist ()
  2923.   "Build `dired-subdir-alist' by parsing the buffer and return it's new value."
  2924.   (interactive)
  2925.   (dired-clear-alist)
  2926.   (save-excursion
  2927.     (let ((count 0))
  2928.       (goto-char (point-min))
  2929.       (setq dired-subdir-alist nil)
  2930.       (while (re-search-forward dired-subdir-regexp nil t)
  2931.     (setq count (1+ count))
  2932.     (dired-alist-add-1 (buffer-substring (match-beginning 1)
  2933.                          (match-end 1))
  2934.              ;; Put subdir boundary between lines:
  2935.              (save-excursion
  2936.                (goto-char (match-beginning 0))
  2937.                (beginning-of-line)
  2938.                (point-marker)))
  2939.     (message "%d" count))
  2940.       (message "%d director%s." count (if (= 1 count) "y" "ies"))
  2941.       ;; We don't need to sort it because it is in buffer order per
  2942.       ;; constructionem.  Return new alist:
  2943.       dired-subdir-alist)))
  2944.  
  2945. (defun dired-alist-add (dir new-marker)
  2946.   ;; Add new DIR at NEW-MARKER.  Sort alist.
  2947.   (dired-alist-add-1 dir new-marker)
  2948.   (dired-alist-sort))
  2949.  
  2950. (defun dired-alist-add-1 (dir new-marker)
  2951.   ;; Add new DIR at NEW-MARKER.  Don't sort.
  2952.   (setq dired-subdir-alist
  2953.     (cons (cons (dired-normalize-subdir dir) new-marker)
  2954.           dired-subdir-alist)))
  2955.  
  2956. (defun dired-alist-sort ()
  2957.   ;; Keep the alist sorted on buffer position.
  2958.   (setq dired-subdir-alist
  2959.     (sort dired-subdir-alist
  2960.           (function (lambda (elt1 elt2)
  2961.               (> (dired-get-subdir-min elt1)
  2962.                  (dired-get-subdir-min elt2)))))))
  2963.  
  2964. (defun dired-unsubdir (dir)
  2965.   ;; Remove DIR from the alist
  2966.   (setq dired-subdir-alist
  2967.     (delq (assoc dir dired-subdir-alist) dired-subdir-alist)))
  2968.  
  2969. (defun dired-goto-next-nontrivial-file ()
  2970.   ;; Position point on first nontrivial file after point.
  2971.   (dired-goto-next-file);; so there is a file to compare with
  2972.   (if (stringp dired-trivial-filenames)
  2973.       (while (and (not (eobp))
  2974.           (string-match dired-trivial-filenames
  2975.                 (file-name-nondirectory
  2976.                  (or (dired-get-filename nil t) ""))))
  2977.     (forward-line 1)
  2978.     (dired-move-to-filename))))
  2979.  
  2980. (defun dired-goto-next-file ()
  2981.   (let ((max (1- (dired-subdir-max))))
  2982.     (while (and (not (dired-move-to-filename)) (< (point) max))
  2983.       (forward-line 1))))
  2984.  
  2985. (defun dired-goto-subdir (dir)
  2986.   "Goto end of header line of DIR in this dired buffer.
  2987. Return value of point on success, otherwise return nil.
  2988. The next char is either \\n, or \\r if DIR is hidden."
  2989.   (interactive
  2990.    (prog1                ; let push-mark display its message
  2991.        (list (expand-file-name
  2992.           (completing-read "Goto in situ directory: " ; prompt
  2993.                    dired-subdir-alist ; table
  2994.                    nil    ; predicate
  2995.                    t    ; require-match
  2996.                    (dired-current-directory))))
  2997.      (push-mark)))
  2998.   (setq dir (file-name-as-directory dir))
  2999.   (let ((elt (assoc dir dired-subdir-alist)))
  3000.     (and elt
  3001.      (goto-char (dired-get-subdir-min elt))
  3002.      ;; dired-subdir-hidden-p and dired-add-entry depend on point being
  3003.      ;; at either \r or \n after this function succeeds.
  3004.      (progn (skip-chars-forward "^\r\n")
  3005.         (point)))))
  3006.  
  3007. (defun dired-goto-file (file)
  3008.   "Goto file line of FILE in this dired buffer."
  3009.   ;; Return value of point on success, else nil.
  3010.   ;; FILE must be an absolute pathname.
  3011.   ;; Loses if FILE contains control chars like "\007" for which ls
  3012.   ;; either inserts "?" or "\\007" into the buffer, so we won't find
  3013.   ;; it in the buffer.
  3014.   (interactive
  3015.    (prog1                ; let push-mark display its message
  3016.        (list (expand-file-name
  3017.           (read-file-name "Goto file: "
  3018.                   (dired-current-directory))))
  3019.      (push-mark)))
  3020.   (setq file (directory-file-name file)) ; does no harm if no directory
  3021.   (let (found case-fold-search)
  3022.     (save-excursion
  3023.       (if (dired-goto-subdir (or (file-name-directory file)
  3024.                  (error "Need absolute pathname for %s" file)))
  3025.       (let ((base (file-name-nondirectory file))
  3026.         (boundary (dired-subdir-max)))
  3027.         (while (and (not found)
  3028.             ;; filenames are preceded by SPC, this makes
  3029.             ;; the search faster (e.g. for the filename "-"!).
  3030.             (search-forward (concat " " base) boundary 'move))
  3031.           ;; Match could have BASE just as initial substring or
  3032.           ;; or in permission bits or date or
  3033.           ;; not be a proper filename at all:
  3034.           (if (equal base (dired-get-filename 'no-dir t))
  3035.             ;; Must move to filename since an (actually
  3036.             ;; correct) match could have been elsewhere on the
  3037.             ;; ;; line (e.g. "-" would match somewhere in the
  3038.             ;; permission bits).
  3039.           (setq found (dired-move-to-filename)))))))
  3040.     (and found
  3041.      ;; return value of point (i.e., FOUND):
  3042.      (goto-char found))))
  3043.  
  3044. (defun dired-initial-position (dirname)
  3045.   ;; Where point should go in a new listing of DIRNAME.
  3046.   ;; Point assumed at beginning of new subdir line.
  3047.   ;; You may redefine this function as you wish, e.g. like in dired-x.el.
  3048.   (end-of-line)
  3049.   (if dired-trivial-filenames (dired-goto-next-nontrivial-file)))
  3050.  
  3051. ;;; moving by subdirectories
  3052.  
  3053. (defun dired-subdir-index (dir)
  3054.   ;; Return an index into alist for use with nth
  3055.   ;; for the sake of subdir moving commands.
  3056.   (let (found (index 0) (alist dired-subdir-alist))
  3057.     (while alist
  3058.       (if (string= dir (car (car alist)))
  3059.       (setq alist nil found t)
  3060.     (setq alist (cdr alist) index (1+ index))))
  3061.     (if found index nil)))
  3062.  
  3063. (defun dired-next-subdir (arg &optional no-error-if-not-found no-skip)
  3064.   "Go to next subdirectory, regardless of level."
  3065.   ;; Use 0 arg to go to this directory's header line.
  3066.   ;; NO-SKIP prevents moving to end of header line, returning whatever
  3067.   ;; position was found in dired-subdir-alist.
  3068.   (interactive "p")
  3069.   (let ((this-dir (dired-current-directory))
  3070.     pos index)
  3071.     ;; nth with negative arg does not return nil but the first element
  3072.     (setq index (- (dired-subdir-index this-dir) arg))
  3073.     (setq pos (if (>= index 0)
  3074.           (dired-get-subdir-min (nth index dired-subdir-alist))))
  3075.     (if pos
  3076.     (progn
  3077.       (goto-char pos)
  3078.       (or no-skip (skip-chars-forward "^\n\r"))
  3079.       (point))
  3080.       (if no-error-if-not-found
  3081.       nil                ; return nil if not found
  3082.     (error "%s directory" (if (> arg 0) "Last" "First"))))))
  3083.  
  3084. (defun dired-prev-subdir (arg &optional no-error-if-not-found no-skip)
  3085.   "Go to previous subdirectory, regardless of level.
  3086. When called interactively and not on a subdir line, go to this subdir's line."
  3087.   ;;(interactive "p")
  3088.   (interactive
  3089.    (list (if current-prefix-arg
  3090.          (prefix-numeric-value current-prefix-arg)
  3091.        ;; if on subdir start already, don't stay there!
  3092.        (if (dired-get-subdir) 1 0))))
  3093.   (dired-next-subdir (- arg) no-error-if-not-found no-skip))
  3094.  
  3095. (defun dired-tree-up (arg)
  3096.   "Go up ARG levels in the dired tree."
  3097.   (interactive "p")
  3098.   (let ((dir (dired-current-directory)))
  3099.     (while (>= arg 1)
  3100.       (setq arg (1- arg)
  3101.         dir (file-name-directory (directory-file-name dir))))
  3102.     ;;(setq dir (expand-file-name dir))
  3103.     (or (dired-goto-subdir dir)
  3104.     (error "Cannot go up to %s - not in this tree." dir))))
  3105.  
  3106. (defun dired-tree-down ()
  3107.   "Go down in the dired tree."
  3108.   (interactive)
  3109.   (let ((dir (dired-current-directory)) ; has slash
  3110.     pos case-fold-search)        ; filenames are case sensitive
  3111.     (let ((rest (reverse dired-subdir-alist)) elt)
  3112.       (while rest
  3113.     (setq elt (car rest)
  3114.           rest (cdr rest))
  3115.     (if (dired-in-this-tree (directory-file-name (car elt)) dir)
  3116.         (setq rest nil
  3117.           pos (dired-goto-subdir (car elt))))))
  3118.     (if pos
  3119.     (goto-char pos)
  3120.       (error "At the bottom"))))
  3121.  
  3122. ;;; hiding
  3123.  
  3124. (defun dired-subdir-hidden-p (dir)
  3125.   (and selective-display
  3126.        (save-excursion
  3127.      (dired-goto-subdir dir)
  3128.      (looking-at "\r"))))
  3129.  
  3130. (defun dired-unhide-subdir ()
  3131.   (let (buffer-read-only)
  3132.     (subst-char-in-region (dired-subdir-min) (dired-subdir-max) ?\r ?\n)))
  3133.  
  3134. (defun dired-hide-check ()
  3135.   (or selective-display
  3136.       (error "selective-display must be t for subdir hiding to work!")))
  3137.  
  3138. (defun dired-hide-subdir (arg)
  3139.   "Hide or unhide the current subdirectory and move to next directory.
  3140. Optional prefix arg is a repeat factor.
  3141. Use \\[dired-hide-all] to (un)hide all directories."
  3142.   (interactive "p")
  3143.   (dired-hide-check)
  3144.   (while (>=  (setq arg (1- arg)) 0)
  3145.     (let* ((cur-dir (dired-current-directory))
  3146.        (hidden-p (dired-subdir-hidden-p cur-dir))
  3147.        (elt (assoc cur-dir dired-subdir-alist))
  3148.        (end-pos (1- (dired-get-subdir-max elt)))
  3149.        buffer-read-only)
  3150.       ;; keep header line visible, hide rest
  3151.       (goto-char (dired-get-subdir-min elt))
  3152.       (skip-chars-forward "^\n\r")
  3153.       (if hidden-p
  3154.       (subst-char-in-region (point) end-pos ?\r ?\n)
  3155.     (subst-char-in-region (point) end-pos ?\n ?\r)))
  3156.     (dired-next-subdir 1 t)))
  3157.  
  3158. (defun dired-hide-all (arg)
  3159.   "Hide all subdirectories, leaving only their header lines.
  3160. If there is already something hidden, make everything visible again.
  3161. Use \\[dired-hide-subdir] to (un)hide a particular subdirectory."
  3162.   (interactive "P")
  3163.   (dired-hide-check)
  3164.   (let (buffer-read-only)
  3165.     (if (save-excursion
  3166.       (goto-char (point-min))
  3167.       (search-forward "\r" nil t))
  3168.     ;; unhide - bombs on \r in filenames
  3169.     (subst-char-in-region (point-min) (point-max) ?\r ?\n)
  3170.       ;; hide
  3171.       (let ((pos (point-max))        ; pos of end of last directory
  3172.         (alist dired-subdir-alist))
  3173.     (while alist            ; while there are dirs before pos
  3174.       (subst-char-in-region (dired-get-subdir-min (car alist)) ; pos of prev dir
  3175.                 (save-excursion
  3176.                   (goto-char pos) ; current dir
  3177.                   ;; we're somewhere on current dir's line
  3178.                   (forward-line -1)
  3179.                   (point))
  3180.                 ?\n ?\r)
  3181.       (setq pos (dired-get-subdir-min (car alist)))    ; prev dir gets current dir
  3182.       (setq alist (cdr alist)))))))
  3183.  
  3184.  
  3185. ;; This function is the heart of tree dired.
  3186. ;; It is called for each retrieved filename.
  3187. ;; It could stand to be faster, though it's mostly function call
  3188. ;; overhead.  Avoiding to funcall seems to save about 10% in
  3189. ;; dired-get-filename.  Make it a defsubst?
  3190. (defun dired-current-directory (&optional localp)
  3191.   "Return the name of the subdirectory to which this line belongs.
  3192. This returns a string with trailing slash, like `default-directory'.
  3193. Optional argument means return a file name relative to `default-directory'."
  3194.   (let ((here (point))
  3195.     (alist (or dired-subdir-alist
  3196.            ;; probably because called in a non-dired buffer
  3197.            (error "No subdir-alist in %s" (current-buffer))))
  3198.     elt dir)
  3199.     (while alist
  3200.       (setq elt (car alist)
  3201.         dir (car elt)
  3202.         ;; use `<=' (not `<') as subdir line is part of subdir
  3203.         alist (if (<= (dired-get-subdir-min elt) here)
  3204.               nil        ; found
  3205.             (cdr alist))))
  3206.     (if localp
  3207.     (dired-make-relative dir default-directory)
  3208.       dir)))
  3209.  
  3210. ;; Subdirs start at the beginning of their header lines and end just
  3211. ;; before the beginning of the next header line (or end of buffer).
  3212.  
  3213. (defun dired-subdir-min ()
  3214.   (save-excursion
  3215.     (if (not (dired-prev-subdir 0 t t))
  3216.     (error "Not in a subdir!")
  3217.       (point))))
  3218.  
  3219. (defun dired-subdir-max ()
  3220.   (save-excursion
  3221.     (if (not (dired-next-subdir 1 t t))
  3222.     (point-max)
  3223.       (point))))
  3224.  
  3225. (defun dired-kill-line-or-subdir (&optional arg)
  3226.   "Kill this line (but not this file).
  3227. Optional prefix argument is a repeat factor.
  3228. If file is displayed as in situ subdir, kill that as well.
  3229. If on a subdir headerline, kill whole subdir."
  3230.   (interactive "p")
  3231.   (if (dired-get-subdir)
  3232.       (dired-kill-subdir)
  3233.     (dired-kill-line arg)))
  3234.  
  3235. (defun dired-kill-line (&optional arg)
  3236.   (interactive "P")
  3237.   (setq arg (prefix-numeric-value arg))
  3238.   (let (buffer-read-only file)
  3239.     (while (/= 0 arg)
  3240.       (setq file (dired-get-filename nil t))
  3241.       (if (not file)
  3242.       (error "Can only kill file lines.")
  3243.     (save-excursion (and file
  3244.                  (dired-goto-subdir file)
  3245.                  (dired-kill-subdir)))
  3246.     (delete-region (progn (beginning-of-line) (point))
  3247.                (progn (forward-line 1) (point)))
  3248.     (if (> arg 0)
  3249.         (setq arg (1- arg))
  3250.       (setq arg (1+ arg))
  3251.       (forward-line -1))))
  3252.     (dired-move-to-filename)))
  3253.  
  3254. (defun dired-kill-subdir (&optional remember-marks)
  3255.   "Remove all lines of current subdirectory.
  3256. Lower levels are unaffected."
  3257.   ;; With optional REMEMBER-MARKS, return a mark-alist.
  3258.   (interactive)
  3259.   (let ((beg (dired-subdir-min))
  3260.     (end (dired-subdir-max))
  3261.     buffer-read-only cur-dir)
  3262.     (setq cur-dir (dired-current-directory))
  3263.     (if (equal cur-dir default-directory)
  3264.     (error "Attempt to kill top level directory"))
  3265.     (prog1
  3266.     (if remember-marks (dired-remember-marks beg end))
  3267.       (delete-region beg end)
  3268.       (if (eobp)            ; don't leave final blank line
  3269.       (delete-char -1))
  3270.       (dired-unsubdir cur-dir))))
  3271.  
  3272. (defun dired-do-kill (&optional arg fmt)
  3273.   "Kill all marked lines (not files).
  3274. With a prefix arg, kill all lines not marked or flagged."
  3275.   ;; Returns count of killed lines.  FMT="" suppresses message.
  3276.   (interactive "P")
  3277.   (save-excursion
  3278.     (goto-char (point-min))
  3279.     (let (buffer-read-only (count 0))
  3280.       (if (not arg)            ; kill marked lines
  3281.       (let ((regexp (dired-marker-regexp)))
  3282.         (while (and (not (eobp))
  3283.             (re-search-forward regexp nil t))
  3284.           (setq count (1+ count))
  3285.           (delete-region (progn (beginning-of-line) (point))
  3286.                  (progn (forward-line 1) (point)))))
  3287.     ;; else kill unmarked lines
  3288.     (while (not (eobp))
  3289.       (if (or (dired-between-files)
  3290.           (not (looking-at "^  ")))
  3291.           (forward-line 1)
  3292.         (setq count (1+ count))
  3293.         (delete-region (point) (save-excursion
  3294.                      (forward-line 1)
  3295.                      (point))))))
  3296.       (or (equal "" fmt)
  3297.       (message (or fmt "Killed %d line%s.") count (dired-plural-s count)))
  3298.       count)))
  3299.  
  3300. (defun dired-do-redisplay (&optional arg test-for-subdir)
  3301.   "Redisplay all marked (or next ARG) files.
  3302.  
  3303. If on a subdir line, redisplay that subdirectory.  In that case,
  3304. a prefix arg lets you edit the ls switches used for the new listing."
  3305.   ;; Moves point if the next ARG files are redisplayed.
  3306.   (interactive "P\np")
  3307.   (if (and test-for-subdir (dired-get-subdir))
  3308.       (dired-insert-subdir
  3309.        (dired-get-subdir)
  3310.        (if arg (read-string "Switches for listing: " dired-actual-switches)))
  3311.     (message "Redisplaying...")
  3312.     ;; message instead of making dired-mark-map show-progress is much faster
  3313.     (dired-mark-map (let ((fname (dired-get-filename)))
  3314.               (message "Redisplaying... %s" fname)
  3315.               (dired-update-file-line fname))
  3316.             arg)
  3317.     (dired-move-to-filename)
  3318.     (message "Redisplaying...done")))
  3319.  
  3320. (defun dired-mark-files-in-region (start end)
  3321.   (let (buffer-read-only)
  3322.     (if (> start end)
  3323.     (error "start > end"))
  3324.     (goto-char start)            ; assumed at beginning of line
  3325.     (while (< (point) end)
  3326.       ;; Skip subdir line and following garbage like the `total' line:
  3327.       (while (and (< (point) end) (dired-between-files))
  3328.     (forward-line 1))
  3329.       (if (and (not (looking-at dired-re-dot))
  3330.            (dired-get-filename nil t))
  3331.       (progn
  3332.         (delete-char 1)
  3333.         (insert dired-marker-char)))
  3334.       (forward-line 1))))
  3335.  
  3336. (defun dired-mark-subdir-files ()
  3337.   "Mark all files except `.' and `..'."
  3338.   (interactive "P")
  3339.   (let ((p-min (dired-subdir-min)))
  3340.     (dired-mark-files-in-region p-min (dired-subdir-max))))
  3341.  
  3342. (defun dired-mark-subdir-or-file (arg)
  3343.   "Mark the current (or next ARG) files.
  3344. If on a subdir headerline, mark all its files except `.' and `..'.
  3345.  
  3346. Use \\[dired-unflag-all-files] to remove all marks
  3347. and \\[dired-unmark-subdir-or-file] on a subdir to remove the marks in
  3348. this subdir."
  3349.   (interactive "P")
  3350.   (if (dired-get-subdir)
  3351.       (save-excursion (dired-mark-subdir-files))
  3352.     (dired-mark-file (prefix-numeric-value arg))))
  3353.  
  3354. (defun dired-unmark-subdir-or-file (arg)
  3355.   "Unmark the current (or next ARG) files.
  3356. If looking at a subdir, unmark all its files except `.' and `..'."
  3357.   (interactive "P")
  3358.   (let ((dired-marker-char ?\040))
  3359.     (dired-mark-subdir-or-file arg)))
  3360.  
  3361. ;;; 5K
  3362. ;;;###begin dired-ins.el
  3363.  
  3364. (defun dired-maybe-insert-subdir (dirname &optional
  3365.                       switches no-error-if-not-dir-p)
  3366.   "Insert this subdirectory into the same dired buffer.
  3367. If it is already present, just move to it (type \\[dired-do-redisplay] to refresh),
  3368.   else inserts it at its natural place (as ls -lR would have done).
  3369. With a prefix arg, you may edit the ls switches used for this listing.
  3370.   You can add `R' to the switches to expand the whole tree starting at
  3371.   this subdirectory.
  3372. This function takes some pains to conform to ls -lR output."
  3373.   (interactive
  3374.    (list (dired-get-filename)
  3375.      (if current-prefix-arg
  3376.          (read-string "Switches for listing: " dired-actual-switches))))
  3377.   (let ((opoint (point)))
  3378.     ;; We don't need a marker for opoint as the subdir is always
  3379.     ;; inserted *after* opoint.
  3380.     (setq dirname (file-name-as-directory dirname))
  3381.     (or (and (not switches)
  3382.          (dired-goto-subdir dirname))
  3383.     (dired-insert-subdir dirname switches no-error-if-not-dir-p))
  3384.     ;; Push mark so that it's easy to find back.  Do this after the
  3385.     ;; insert message so that the user sees the `Mark set' message.
  3386.     (push-mark opoint)))
  3387.  
  3388. (defun dired-insert-subdir (dirname &optional switches no-error-if-not-dir-p)
  3389.   "Insert this subdirectory into the same dired buffer.
  3390. If it is already present, overwrites previous entry,
  3391.   else inserts it at its natural place (as ls -lR would have done).
  3392. With a prefix arg, you may edit the ls switches used for this listing.
  3393.   You can add `R' to the switches to expand the whole tree starting at
  3394.   this subdirectory.
  3395. This function takes some pains to conform to ls -lR output."
  3396.   ;; NO-ERROR-IF-NOT-DIR-P needed for special filesystems like
  3397.   ;; Prospero where dired-ls does the right thing, but
  3398.   ;; file-directory-p has not been redefined.
  3399.   (interactive
  3400.    (list (dired-get-filename)
  3401.      (if current-prefix-arg
  3402.          (read-string "Switches for listing: " dired-actual-switches))))
  3403.   (setq dirname (file-name-as-directory (expand-file-name dirname)))
  3404.   (dired-insert-subdir-validate dirname switches)
  3405.   (or no-error-if-not-dir-p
  3406.       (file-directory-p dirname)
  3407.       (error  "Attempt to insert a non-directory: %s" dirname))
  3408.   (let ((elt (assoc dirname dired-subdir-alist))
  3409.      switches-have-R mark-alist case-fold-search buffer-read-only)
  3410.     ;; case-fold-search is nil now, so we can test for capital `R':
  3411.     (if (setq switches-have-R (and switches (string-match "R" switches)))
  3412.     ;; avoid duplicated subdirs
  3413.     (setq mark-alist (dired-kill-tree dirname t)))
  3414.     (if elt
  3415.     ;; If subdir is already present, remove it and remember its marks
  3416.     (setq mark-alist (nconc (dired-insert-subdir-del elt) mark-alist))
  3417.       (dired-insert-subdir-newpos dirname)) ; else compute new position
  3418.     (dired-insert-subdir-doupdate
  3419.      dirname elt (dired-insert-subdir-doinsert dirname switches))
  3420.     (if switches-have-R (dired-build-subdir-alist))
  3421.     (dired-initial-position dirname)
  3422.     (save-excursion (dired-mark-remembered mark-alist))))
  3423.  
  3424. ;; This is a separate function for dired-vms.
  3425. (defun dired-insert-subdir-validate (dirname &optional switches)
  3426.   ;; Check that it is valid to insert DIRNAME with SWITCHES.
  3427.   ;; Signal an error if invalid (e.g. user typed `i' on `..').
  3428.   (or (dired-in-this-tree dirname default-directory)
  3429.       (error  "%s: not in this directory tree" dirname))
  3430.   (if switches
  3431.       (let (case-fold-search)
  3432.     (mapcar
  3433.      (function
  3434.       (lambda (x)
  3435.         (or (eq (null (string-match x switches))
  3436.             (null (string-match x dired-actual-switches)))
  3437.         (error "Can't have dirs with and without -%s switches together"
  3438.                x))))
  3439.      ;; all switches that make a difference to dired-get-filename:
  3440.      '("F" "b")))))
  3441.  
  3442. (defun dired-kill-tree (dirname &optional remember-marks)
  3443.   ;;"Kill all proper subdirs of DIRNAME, excluding DIRNAME itself.
  3444.   ;; With optional arg REMEMBER-MARKS, return an alist of marked files."
  3445.   (interactive "DKill tree below directory: ")
  3446.   (let ((s-alist dired-subdir-alist) dir m-alist)
  3447.     (while s-alist
  3448.       (setq dir (car (car s-alist))
  3449.         s-alist (cdr s-alist))
  3450.       (if (and (not (string-equal dir dirname))
  3451.            (dired-in-this-tree dir dirname)
  3452.            (dired-goto-subdir dir))
  3453.       (setq m-alist (nconc (dired-kill-subdir remember-marks) m-alist))))
  3454.     m-alist))
  3455.  
  3456. (defun dired-insert-subdir-newpos (new-dir)
  3457.   ;; Find pos for new subdir, according to tree order.
  3458.   (let ((alist dired-subdir-alist) elt dir pos new-pos)
  3459.     (while alist
  3460.       (setq elt (car alist)
  3461.         alist (cdr alist)
  3462.         dir (car elt)
  3463.         pos (dired-get-subdir-min elt))
  3464.       (if (dired-tree-lessp dir new-dir)
  3465.       ;; Insert NEW-DIR after DIR
  3466.       (setq new-pos (dired-get-subdir-max elt)
  3467.         alist nil)))
  3468.     (goto-char new-pos))
  3469.   ;; want a separating newline between subdirs
  3470.   (or (eobp)
  3471.       (forward-line -1))
  3472.   (insert "\n")
  3473.   (point))
  3474.  
  3475. (defun dired-insert-subdir-del (element)
  3476.   ;; Erase an already present subdir (given by ELEMENT) from buffer.
  3477.   ;; Move to that buffer position.  Return a mark-alist.
  3478.   (let ((begin-marker (dired-get-subdir-min element)))
  3479.     (goto-char begin-marker)
  3480.     ;; Are at beginning of subdir (and inside it!).  Now determine its end:
  3481.     (goto-char (dired-subdir-max))
  3482.     (or (eobp);; want a separating newline _between_ subdirs:
  3483.     (forward-char -1))
  3484.     (prog1
  3485.     (dired-remember-marks begin-marker (point))
  3486.       (delete-region begin-marker (point)))))
  3487.  
  3488. (defun dired-insert-subdir-doinsert (dirname switches)
  3489.   ;; Insert ls output after point and put point on the correct
  3490.   ;; position for the subdir alist.
  3491.   ;; Return the boundary of the inserted text (as list of BEG and END).
  3492.   (let ((begin (point)) end)
  3493.     (message "Reading directory %s..." dirname)
  3494.     (let ((dired-actual-switches
  3495.        (or switches
  3496.            (dired-replace-in-string "R" "" dired-actual-switches))))
  3497.       (if (equal dirname (car (car (reverse dired-subdir-alist))))
  3498.       ;; top level directory may contain wildcards:
  3499.       (dired-readin-insert dired-directory)
  3500.     (dired-ls dirname dired-actual-switches nil t)))
  3501.     (message "Reading directory %s...done" dirname)
  3502.     (setq end (point-marker))
  3503.     (indent-rigidly begin end 2)
  3504.     ;;  call dired-insert-headerline afterwards, as under VMS dired-ls
  3505.     ;;  does insert the headerline itself and the insert function just
  3506.     ;;  moves point.
  3507.     ;;  Need a marker for END as this inserts text.
  3508.     (goto-char begin)
  3509.     (dired-insert-headerline dirname)
  3510.     ;; point is now like in dired-build-subdir-alist
  3511.     (prog1
  3512.     (list begin (marker-position end))
  3513.       (set-marker end nil))))
  3514.  
  3515. (defun dired-insert-subdir-doupdate (dirname elt beg-end)
  3516.   ;; Point is at the correct subdir alist position for ELT,
  3517.   ;; BEG-END is the subdir-region (as list of begin and end).
  3518.   (if elt                ; subdir was already present
  3519.       ;; update its position (should actually be unchanged)
  3520.       (set-marker (dired-get-subdir-min elt) (point-marker))
  3521.     (dired-alist-add dirname (point-marker)))
  3522.   ;; The hook may depend on the subdir-alist containing the just
  3523.   ;; inserted subdir, so run it after dired-alist-add:
  3524.   (if dired-after-readin-hook
  3525.       (save-excursion
  3526.     (let ((begin (nth 0 beg-end))
  3527.           (end (nth 1 beg-end)))
  3528.       (goto-char begin)
  3529.       (save-restriction
  3530.         (narrow-to-region begin end)
  3531.         ;; hook may add or delete lines, but the subdir boundary
  3532.         ;; marker floats
  3533.         (run-hooks 'dired-after-readin-hook))))))
  3534.  
  3535. (defun dired-tree-lessp (dir1 dir2)
  3536.   ;; Lexicographic order on pathname components, like `ls -lR':
  3537.   ;; DIR1 < DIR2 iff DIR1 comes *before* DIR2 in an `ls -lR' listing,
  3538.   ;;   i.e., iff DIR1 is a (grand)parent dir of DIR2,
  3539.   ;;   or DIR1 and DIR2 are in the same parentdir and their last
  3540.   ;;   components are string-lessp.
  3541.   ;; Thus ("/usr/" "/usr/bin") and ("/usr/a/" "/usr/b/") are tree-lessp.
  3542.   ;; string-lessp could arguably be replaced by file-newer-than-file-p
  3543.   ;;   if dired-actual-switches contained `t'.
  3544.   (setq dir1 (file-name-as-directory dir1)
  3545.     dir2 (file-name-as-directory dir2))
  3546.   (let ((components-1 (dired-split "/" dir1))
  3547.     (components-2 (dired-split "/" dir2)))
  3548.     (while (and components-1
  3549.         components-2
  3550.         (equal (car components-1) (car components-2)))
  3551.       (setq components-1 (cdr components-1)
  3552.         components-2 (cdr components-2)))
  3553.     (let ((c1 (car components-1))
  3554.       (c2 (car components-2)))
  3555.  
  3556.       (cond ((and c1 c2)
  3557.          (string-lessp c1 c2))
  3558.         ((and (null c1) (null c2))
  3559.          nil)            ; they are equal, not lessp
  3560.         ((null c1)            ; c2 is a subdir of c1: c1<c2
  3561.          t)
  3562.         ((null c2)            ; c1 is a subdir of c2: c1>c2
  3563.          nil)
  3564.         (t (error "This can't happen"))))))
  3565.  
  3566. ;; There should be a builtin split function - inverse to mapconcat.
  3567. (defun dired-split (pat str &optional limit)
  3568.   "Splitting on regexp PAT, turn string STR into a list of substrings.
  3569. Optional third arg LIMIT (>= 1) is a limit to the length of the
  3570. resulting list.
  3571. Thus, if SEP is a regexp that only matches itself,
  3572.  
  3573.    (mapconcat 'identity (dired-split SEP STRING) SEP)
  3574.  
  3575. is always equal to STRING."
  3576.   (let* ((start (string-match pat str))
  3577.      (result (list (substring str 0 start)))
  3578.      (count 1)
  3579.      (end (if start (match-end 0))))
  3580.     (if end                ; else nothing left
  3581.     (while (and (or (not (integerp limit))
  3582.             (< count limit))
  3583.             (string-match pat str end))
  3584.       (setq start (match-beginning 0)
  3585.         count (1+ count)
  3586.         result (cons (substring str end start) result)
  3587.         end (match-end 0)
  3588.         start end)
  3589.       ))
  3590.     (if (and (or (not (integerp limit))
  3591.          (< count limit))
  3592.          end)            ; else nothing left
  3593.     (setq result
  3594.           (cons (substring str end) result)))
  3595.     (nreverse result)))
  3596.  
  3597. ;;;###end dired-ins.el
  3598.  
  3599.  
  3600. ;;; Sorting
  3601.  
  3602. ;; Most ls can only sort by name or by date (with -t), nothing else.
  3603. ;; GNU ls sorts on size with -S, on extension with -X, and unsorted with -U.
  3604. ;; So anything that does not contain these is sort "by name".
  3605.  
  3606. (defvar dired-ls-sorting-switches "SXU"
  3607.   "String of ls switches (single letters) except `t' that influence sorting.")
  3608.  
  3609. (defvar dired-sort-by-date-regexp
  3610.   (concat "^-[^" dired-ls-sorting-switches
  3611.       "]*t[^" dired-ls-sorting-switches "]*$")
  3612.   "Regexp recognized by dired to set `by date' mode.")
  3613.  
  3614. (defvar dired-sort-by-name-regexp
  3615.   (concat "^-[^t" dired-ls-sorting-switches "]+$")
  3616.   "Regexp recognized by dired to set `by name' mode.")
  3617.  
  3618. (defvar dired-sort-mode nil
  3619.   "Whether Dired sorts by name, date etc. (buffer-local).")
  3620. ;; This is nil outside dired buffers so it can be used in the modeline
  3621.  
  3622. (defun dired-sort-set-modeline ()
  3623.   ;; Set modeline display according to dired-actual-switches.
  3624.   ;; Modeline display of "by name" or "by date" guarantees the user a
  3625.   ;; match with the corresponding regexps.  Non-matching switches are
  3626.   ;; shown literally.
  3627.   (setq dired-sort-mode
  3628.     (let (case-fold-search)
  3629.       (cond ((string-match dired-sort-by-name-regexp dired-actual-switches)
  3630.          " by name")
  3631.         ((string-match dired-sort-by-date-regexp dired-actual-switches)
  3632.          " by date")
  3633.         (t
  3634.          (concat " " dired-actual-switches)))))
  3635.   ;; update mode line:
  3636.   (set-buffer-modified-p (buffer-modified-p)))
  3637.  
  3638. (defun dired-sort-toggle-or-edit (&optional arg)
  3639.   "Toggle between sort by date/name and refresh the dired buffer.
  3640. With a prefix argument you can edit the current listing switches instead."
  3641.   (interactive "P")
  3642.   (if arg
  3643.       (dired-sort-other
  3644.        (read-string "ls switches (must contain -l): " dired-actual-switches))
  3645.     (dired-sort-toggle)))
  3646.  
  3647. (defun dired-sort-toggle ()
  3648.   ;; Toggle between sort by date/name.  Reverts the buffer.
  3649.   (setq dired-actual-switches
  3650.     (let (case-fold-search)
  3651.       (concat
  3652.        "-l"
  3653.        (dired-replace-in-string (concat "[---lt"
  3654.                         dired-ls-sorting-switches "]")
  3655.                     ""
  3656.                     dired-actual-switches)
  3657.        (if (string-match (concat "[t" dired-ls-sorting-switches "]")
  3658.                  dired-actual-switches)
  3659.            ""
  3660.          "t"))))
  3661.   (dired-sort-set-modeline)
  3662.   (revert-buffer))
  3663.  
  3664. (defun dired-sort-other (switches &optional no-revert)
  3665.   ;; Specify new ls SWITCHES for current dired buffer.  Values matching
  3666.   ;; `dired-sort-by-date-regexp' or `dired-sort-by-name-regexp' set the
  3667.   ;; minor mode accordingly, others appear literally in the mode line.
  3668.   ;; With optional second arg NO-REVERT, don't refresh the listing afterwards.
  3669.   (setq dired-actual-switches switches)
  3670.   (dired-sort-set-modeline)
  3671.   (or no-revert (revert-buffer)))
  3672.  
  3673. (if (eq system-type 'vax-vms)
  3674.     (load "dired-vms"))
  3675.  
  3676. (run-hooks 'dired-load-hook)        ; for your customizations
  3677.